99 questions/Solutions/14

From HaskellWiki
< 99 questions‎ | Solutions
Revision as of 03:55, 18 November 2010 by Tianyicui (talk | contribs)
Jump to: navigation, search

(*) 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 foldr:

dupli = foldr (\ x xs -> x : x : xs) []