99 questions/Solutions/12: Difference between revisions
< 99 questions | Solutions
Jargonjustin (talk | contribs) No edit summary |
Jargonjustin (talk | contribs) No edit summary |
||
Line 18: | Line 18: | ||
decode :: [(Int, a)] -> [a] | decode :: [(Int, a)] -> [a] | ||
decode = concatMap (uncurry replicate) | decode = concatMap (uncurry replicate) | ||
</haskell> | |||
This can be easily extended given a helper function: | |||
<haskell> | |||
toTuple :: ListItem a -> (Int, a) | |||
toTuple (Single x) = (1, x) | |||
toTuple (Multiple n x) = (n, x) | |||
</haskell> | |||
as: | |||
<haskell> | |||
decode :: [ListItem a] -> [a] | |||
decode = concatMap (uncurry replicate . toTuple) | |||
</haskell> | </haskell> |
Revision as of 05:15, 11 May 2011
(**) Decode a run-length encoded list.
Given a run-length code list generated as specified in problem 11. Construct its uncompressed version.
decodeModified :: [ListItem a] -> [a]
decodeModified = concatMap decodeHelper
where
decodeHelper (Single x) = [x]
decodeHelper (Multiple n x) = replicate n x
We only need to map single instances of an element to a list containing only one element and multiple ones to a list containing the specified number of elements and concatenate these lists.
A solution for the simpler encoding from problem 10 can be given as:
decode :: [(Int, a)] -> [a]
decode = concatMap (uncurry replicate)
This can be easily extended given a helper function:
toTuple :: ListItem a -> (Int, a)
toTuple (Single x) = (1, x)
toTuple (Multiple n x) = (n, x)
as:
decode :: [ListItem a] -> [a]
decode = concatMap (uncurry replicate . toTuple)