99 questions/Solutions/14: Difference between revisions
< 99 questions | Solutions
No edit summary |
mNo edit summary |
||
Line 35: | Line 35: | ||
<haskell> | <haskell> | ||
dupli = foldr (\ x xs -> x : x : xs) [] | dupli = foldr (\ x xs -> x : x : xs) [] | ||
</haskell> | |||
or, using silliness: | |||
<haskell> | |||
dupli = foldr (\x -> ((x:) . (x:)) [] | |||
</haskell> | </haskell> |
Revision as of 21:00, 13 January 2011
(*) Duplicate the elements of a list.
dupli [] = []
dupli (x:xs) = x:x:dupli xs
or, using list comprehension syntax:
dupli list = concat [[x,x] | x <- list]
or, using the list monad:
dupli xs = xs >>= (\x -> [x,x])
or, using concatMap
:
dupli = concatMap (\x -> [x,x])
also using concatMap
:
dupli = concatMap (replicate 2)
or, using foldl
:
dupli = foldl (\acc x -> acc ++ [x,x]) []
or, using foldr
:
dupli = foldr (\ x xs -> x : x : xs) []
or, using silliness:
dupli = foldr (\x -> ((x:) . (x:)) []