Today I started to tackle the 99 Haskell problems (http://www.haskell.org/haskellwiki/99_questions). I had to struggle with problem 9 which requires to Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists..
For example the input:
pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']
["aaaa","b","cc","aa","d","eeee"]
I managed to create a pack
function. However, my solution feels kind of
overcomplicated:
pack :: [[Char]] -> [[Char]]
pack xs = foldl (\acc x -> if not(null acc) && x `Data.List.isPrefixOf` (last acc)
then (init acc) ++ [(last acc) ++ x]
else acc ++ [x]) [] xs
A test of my pack
function:
pack ["a", "a", "b", "b", "b", "c", "a", "a", "c"]
["aa","bbb","c","aa","c"]
- Can you give me a code review?
- How can I simplify it? What could I improve to make this function more idiomatic?
group
function ofData.List
. You could also inspect its source code. \$\endgroup\$