{- |
Description: Run-length encoding of a list
Copyright: Copyright (C) 2021 Yoo Chung
License: GPL-3.0-or-later
Maintainer: dev@chungyc.org

Some solutions to "Problems.P10" of Ninety-Nine Haskell "Problems".
-}
module Solutions.P10 (encode) where

import           Data.Maybe (mapMaybe)
import           Problems.P04
import           Problems.P09

{- |
Use the 'Problems.P09.pack' function to implement
the so-called run-length encoding data compression method.

Consecutive duplicates of elements are encoded as tuples @(n, e)@,
where @n@ is the number of duplicates of the element @e@.
-}
encode :: Eq a => [a] -> [(Int, a)]
encode :: forall a. Eq a => [a] -> [(Int, a)]
encode [a]
xs = ([a] -> Maybe (Int, a)) -> [[a]] -> [(Int, a)]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe [a] -> Maybe (Int, a)
forall {b}. [b] -> Maybe (Int, b)
count ([[a]] -> [(Int, a)]) -> [[a]] -> [(Int, a)]
forall a b. (a -> b) -> a -> b
$ [a] -> [[a]]
forall a. Eq a => [a] -> [[a]]
pack [a]
xs
  where count :: [b] -> Maybe (Int, b)
count [] = Maybe (Int, b)
forall a. Maybe a
Nothing
        count l :: [b]
l@(b
x:[b]
_) = (Int, b) -> Maybe (Int, b)
forall a. a -> Maybe a
Just ([b] -> Int
forall a. [a] -> Int
myLength [b]
l, b
x)