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.

Example:

* (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']
["aaaa","b","cc","aa","d","eeee"]

Solution:

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]]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s