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)) ("","")


 -- 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])


 -- split at whitespace
 -- "hello world" -> ["hello","world"]
 words
 fst . until (null . snd) 
             (\(a,b) -> let (x,y) = break (==' ') b 
                        in (a++[x], drop 1 y)) 
             $ ([], "hello world")


 -- 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)


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


 -- sorting by a custom function
 -- ["abc", "ab", "a"] -> ["a", "ab", "abc"]
 sortBy length
 map snd . sortBy fst . map (length &&& id) 
 
 
 -- 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


 -- add indices to list for later use
 -- [3,3,3] -> [(0,3),(1,3),(2,3)]
 zip [0..]
 

 -- fibonacci series
 unfoldr (\(f1,f2) -> Just (f1,(f2,f1+f2))) (1,1)
 fibs = 1:1:zipWith (+) fibs (tail fibs)
 

 {-
 catMaybes
 either
 maybe
 zipWith (i.e. for adding indices)
 matrix operations with lists of lists
 group
 inits (i.e. don's substring function)
 fun with monad, monadPlus
 -}