Blow your mind

From HaskellWiki
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"]
 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"
 until (null . snd) (\(a,b) -> let (x,y) = span (/=' ') b in (a++[x], drop 1 y)) $ ([], "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


 -- simulating lisp's cond
 case () of () | 1 > 2     -> True
               | 3 < 4     -> False
               | otherwise -> True