Difference between revisions of "99 questions/Solutions/12"
< 99 questions | Solutions
Jump to navigation
Jump to search
m (Improve code layout.) |
(Fix function name) |
||
Line 31: | Line 31: | ||
<haskell> |
<haskell> |
||
− | + | decodeModified :: [ListItem a] -> [a] |
|
− | + | decodeModified = concatMap (uncurry replicate . toTuple) |
|
</haskell> |
</haskell> |
||
a naïve solution with <hask>foldl</hask>: |
a naïve solution with <hask>foldl</hask>: |
||
<haskell> |
<haskell> |
||
− | + | decodeModified :: [ListItem a]-> [a] |
|
− | + | decodeModified = foldl (\x y -> x ++ decodeHelper y) [] |
|
where |
where |
||
decodeHelper :: ListItem a -> [a] |
decodeHelper :: ListItem a -> [a] |
||
Line 48: | Line 48: | ||
<haskell> |
<haskell> |
||
− | + | decodeModified :: [ListItem a] -> [a] |
|
− | + | decodeModified = foldl (\acc e -> case e of Single x -> acc ++ [x]; Multiple n x -> acc ++ replicate n x) [] |
|
</haskell> |
</haskell> |
Revision as of 21:01, 8 April 2013
(**) 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:
decodeModified :: [ListItem a] -> [a]
decodeModified = concatMap (uncurry replicate . toTuple)
a naïve solution with foldl
:
decodeModified :: [ListItem a]-> [a]
decodeModified = foldl (\x y -> x ++ decodeHelper y) []
where
decodeHelper :: ListItem a -> [a]
decodeHelper (Single x) = [x]
decodeHelper (Multiple n x) = replicate n x
foldl
can also be used to solve this problem:
decodeModified :: [ListItem a] -> [a]
decodeModified = foldl (\acc e -> case e of Single x -> acc ++ [x]; Multiple n x -> acc ++ replicate n x) []