Haskell Cheat Sheet

From MCIS Wiki
Jump to: navigation, search

Sections

An infix operation like + or :+: can be placed in parens to create a function which is used in prefix form:

a + b  is the same as  (+) a b

If you put a value on either side of the operator in the parens then you get a "section" - a function which takes one argument and puts it where the missing thing is:

(:+: c 4 en)   -- This is a function which adds a "c" at the end of a piece of music
(c 4 en :+:)   -- This places the eighth note before the music

Anonymous Functions

Using a \ creates an anonymous function:

\x -> x + 1   -- An increment function
\m -> m :=: (rest en :+: m)   -- a function to add an echo
\m1 m2 -> m1 :+: m2 :+: m1    -- an "aba" function

Lists

Create a list:

[1,2,3]

List of numbers:

[1..10]

Return the first element of a list:

head [1,2,3]

Remove the first element from a list:

tail [1,2,3]
drop 1 [1,2,3]   -- This doesn't error out when the list is empty

Join two lists:

[1,2,3] ++ [4,5,6]

Remove a specific number of things from a list:

drop 3 [1,2,3,4,5,6]

Take a specific number of things from a list:

take 3 [1,2,3,4,5,6]

Change everything in a list:

map (+ 1) [1,2,3,4]

Filter a list:

filter (> 4) [2,5,4,9,6]

Reverse a list:

reverse [2,3,4,7]

Repeat infinitely:

take 10 (repeat 7)

Flatten a list:

concat [[2,3],[4,5,6],[10,11]]

Cycle indefinitely:

take 10 (cycle [1,2,3,4])

Join pairwise:

zip [1,2,3] [4,7,5]

Interleave:

concat (map (\(a,b) -> [a,b]) (zip [1,3,6,8] [2,4,6,9]))

Every other:

eo [] = []
eo [x] = [x]
eo (x:y:z) = x : eo z
eo [1,4,3,7,9]

Filter by position:

filterByPos :: (Int -> Bool) -> [a] -> [a]
filterByPos f s = map snd $ filter (\(i,x) -> f i) $ zip [0..] s
filterByPos (\x -> x `mod` 2 == 0) [1,2,3,4,5,6,7]