Blow your mind

From HaskellWiki
Revision as of 02:23, 1 March 2006 by JohannesAhlmann (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Helpful Idioms

 -- splitting in twos (alternating)
 -- "1234567" -> ("1357", "246")
 foldr (\a (x,y) -> (a:y,x)) ("","") "1234567"


 -- splitting in N
 -- 2 -> "1234567" -> ["12", "34", "56", "7"]
 fst . until (null . snd) (\(a,b) -> let (x,y) = splitAt 2 b in (a++[x],y)) $ ([], [1..7])


 -- combinations
 -- "12" -> "45" -> ["14", "15", "24", "25"]
 sequence ["12", "45"]


 -- factorial
 -- 6 -> 720
 product [1..6]
 foldl1 (*) [1..6]
 (!!6) $ unfoldr (\(n,f) -> Just (f, (n+1,f*n))) (1,1)


 -- split at whitespace
 -- "hello world" -> ["hello","world"]
 words "hello world"


 -- interspersing with newlines
 -- ["hello","world"] -> "hello world"
 unlines ["hello","world"]
 intersperse '\n' ["hello","world"]


 -- zweierpotenzen
 iterate (*2) 1
 unfoldr (\z -> Just (z,2*z)) 1