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

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

import           Problems.Lists
import           Problems.P04
import           Problems.P09

{- |
Modify the 'Problems.P10.encode' function in such a way that
if an element has no duplicates it is simply copied into the result list.
Only elements with duplicates are transferred as @('Multiple' n x)@ values.
-}
encodeModified :: Eq a => [a] -> [Encoding a]
encodeModified :: forall a. Eq a => [a] -> [Encoding a]
encodeModified [a]
xs = [[a]] -> [Encoding a]
forall a. [[a]] -> [Encoding a]
encodePacked ([[a]] -> [Encoding a]) -> [[a]] -> [Encoding a]
forall a b. (a -> b) -> a -> b
$ [a] -> [[a]]
forall a. Eq a => [a] -> [[a]]
pack [a]
xs

-- | Turn each sublist in a packed list into an 'Encoding'.
encodePacked :: [[a]] -> [Encoding a]
encodePacked :: forall a. [[a]] -> [Encoding a]
encodePacked []       = []
encodePacked ([]:[[a]]
ls)  = [[a]] -> [Encoding a]
forall a. [[a]] -> [Encoding a]
encodePacked [[a]]
ls
encodePacked ([a
x]:[[a]]
ls) = a -> Encoding a
forall a. a -> Encoding a
Single a
x Encoding a -> [Encoding a] -> [Encoding a]
forall a. a -> [a] -> [a]
: [[a]] -> [Encoding a]
forall a. [[a]] -> [Encoding a]
encodePacked [[a]]
ls
encodePacked (l :: [a]
l@(a
x:[a]
_):[[a]]
ls)   = Int -> a -> Encoding a
forall a. Int -> a -> Encoding a
Multiple ([a] -> Int
forall a. [a] -> Int
myLength [a]
l) a
x Encoding a -> [Encoding a] -> [Encoding a]
forall a. a -> [a] -> [a]
: [[a]] -> [Encoding a]
forall a. [[a]] -> [Encoding a]
encodePacked [[a]]
ls