Difference between revisions of "Blow your mind"

From HaskellWiki
Jump to navigation Jump to search
m
 
m
Line 8: Line 8:
 
-- splitting in N
 
-- splitting in N
 
-- 2 -> "1234567" -> ["12", "34", "56", "7"]
 
-- 2 -> "1234567" -> ["12", "34", "56", "7"]
fst . until (null . snd) (\(a,b) -> let (x,y) = splitAt 2 b in (a++[x],y)) $ ([], [1..7])
+
until (null . snd) (\(a,b) -> let (x,y) = splitAt 2 b in (a++[x],y)) $ ([], [1..7])
   
 
 
Line 26: Line 26:
 
-- "hello world" -> ["hello","world"]
 
-- "hello world" -> ["hello","world"]
 
words "hello world"
 
words "hello world"
  +
until (null . snd) (\(a,b) -> let (x,y) = span (/=' ') b in (a++[x], drop 1 y)) $ ([], "hello world")
   
   
Line 37: Line 38:
 
iterate (*2) 1
 
iterate (*2) 1
 
unfoldr (\z -> Just (z,2*z)) 1
 
unfoldr (\z -> Just (z,2*z)) 1
  +
  +
  +
-- simulating lisp's cond
  +
case () of () | 1 > 2 -> True
  +
| 3 < 4 -> False
  +
| otherwise -> True

Revision as of 02:34, 1 March 2006

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