# 99 questions/Solutions/11

### From HaskellWiki

< 99 questions | Solutions(Difference between revisions)

(Added an alternative solution using list comprehensions.) |
|||

Line 25: | Line 25: | ||

In this case, <hask>ListItem</hask> type can be used from the above solution and <hask>group</hask> can be found in <hask>Data.List</hask> module. | In this case, <hask>ListItem</hask> type can be used from the above solution and <hask>group</hask> can be found in <hask>Data.List</hask> module. | ||

+ | |||

+ | [[Category:Programming exercise spoilers]] |

## 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

encode

Single

Multiple

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

ListItem

group

Data.List