(Added an alternative solution using list comprehensions.)
Latest revision as of 19:31, 18 January 2014
(*) Modified run-length encoding.
Modify the result of problem 10 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 (N E) lists.
data ListItem a = Single a | Multiple Int a deriving (Show) encodeModified :: Eq a => [a] -> [ListItem a] encodeModified = map encodeHelper . encode where encodeHelper (1,x) = Single x encodeHelper (n,x) = Multiple n x
The ListItem definition contains 'deriving (Show)' so that we can get interactive output.
This problem could also be solved using a list comprehension like so:
encodeModified xs = [y | x <- group xs, let y = if (length x) == 1 then Single (head x) else Multiple (length x) (head x)]