Difference between revisions of "99 questions/Solutions/14"

From HaskellWiki
Jump to navigation Jump to search
Line 25: Line 25:
 
<haskell>
 
<haskell>
 
dupli = concatMap (replicate 2)
 
dupli = concatMap (replicate 2)
  +
</haskell>
  +
  +
or, using <hask>foldl</hask>:
  +
<haskell>
  +
dupli = foldl (\acc x -> acc ++ [x,x]) []
 
</haskell>
 
</haskell>
 
 

Revision as of 22:26, 20 December 2010

(*) 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) []