Problem 09

99 Haskell Problems

Problem 9

(**) Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists.


* (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))

Example in Haskell:

*Main> pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 
             'a', 'd', 'e', 'e', 'e', 'e']


pack [] = []
pack [x] = [[x]]
pack (x:xs)
  | elem x (head (pack xs)) = (x:head (pack xs)):tail (pack xs)
  | otherwise = [x]:pack xs

This solution check if x is an element of xs where x is the head of the list and xs is the tail. If x is not in xs (otherwise condition), then x becomes a list itself. Since we pack xs first, we recurse to the last element and build the list of list from there.

Note: Again the signature of pack must be a list of element that can be compare equality

:t pack
pack :: Eq a => [a] -> [[a]]