From f4496a8648e8c2a7c7b60b6b2ef3c90ecaba20bf Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Tue, 21 Nov 2023 15:21:21 +0700 Subject: [PATCH] Haskell: Exercise #9 --- Haskell.org | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/Haskell.org b/Haskell.org index f07bcee..694ba53 100644 --- a/Haskell.org +++ b/Haskell.org @@ -195,3 +195,47 @@ import Data.List compress :: Eq a => [a] -> [a] compress = map head . group #+end_src +*** #9 Pack consecutive duplicates of list elements into sublists + +If a list contains repeated elements they should be placed in separate sublists. + +Example: + +#+begin_src haskell +,* (pack '(a a a a b c c a a d e e e e)) +((A A A A) (B) (C C) (A A) (D) (E E E E)) +#+end_src + +Example in Haskell: + +#+begin_src haskell +λ> pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'] +["aaaa","b","cc","aa","d","eeee"] +#+end_src +**** Solution +In python you can use ~Counter~ +#+begin_src python +from collections import Counter +def pack(arr): + return [[key] * val for key,val in Counter(arr).items()] +#+end_src + +In Haskell, this is just ~group~ + +#+begin_src haskell +pack :: [a] -> [[a]] +pack = group +#+end_src + +Here's my naive implementation + +#+begin_src haskell +pack :: Eq a => [a] -> [[a]] +pack xs = reverse $ go [[]] xs + where + go acc [] = acc + go ([]:acc) (x:xs) = go ([x]:acc) xs + go ((a:as):acc) (x:xs) + | a == x = go ((x:a:as):acc) xs + | otherwise = go ([x]:(a:as):acc) xs +#+end_src