Thursday, May 08, 2014

haskell cheat sheet


=====================================================
simple arithmetic
=====================================================
2 + 3
2 - 3
2 * 3
2 / 3


=====================================================
precedence
=====================================================
(2 * 3) - 4
2 * 3 - 4
2 * (3 - 4)
5 * (-3)


=====================================================
boolean algebra
=====================================================
True && False  
True && True  
False || True  
not False  
not (True && True)  


=====================================================
equality
=====================================================
1 == 1
1 == 0
2 /= 2
2 /= 3
"test" == "test"
"test" /= "test"


=====================================================
function arguments
=====================================================
succ 1
min 4 5
max 1.2 2.3

function application has highest precedence
f g h x == (((f g) h) x)
succ 3 + min 2 3 + 1
(succ 3) + (min 2 3) + 1


=====================================================
infix operators
=====================================================
4 `min` 5 == min 4 5
3 + 4 == (+) 3 4
((==) 3 4) == (3 == 4)


=====================================================
GHCi
=====================================================
Prelude> :type succ
succ :: Enum a => a -> a
Prelude> :info succ
class Enum a where
succ :: a -> a
...
-- Defined in `GHC.Enum'                                                                                                


=====================================================
functions
=====================================================
addThem x y = x + y


=====================================================
if statement
=====================================================
greaterThan10 x =
  if x > 10 then True else False


=====================================================
lists
=====================================================
[]
[1, 2]

1:[2]
1:2:[]

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

[1..10]
[1,3..10]
[1..]

head [1, 2, 3] == 1

tail [1, 2, 3] == [2, 3]

last [1, 2, 3] == 3

init [1, 2, 3] == [1, 2]

length [1, 2, 3] == 3

null [] == True
null [1, 2, 3] == False

reverse [1, 2, 3] == [3, 2, 1]

take 2 [1, 2, 3] == [1, 2]
take 0 [1, 2, 3] == []

drop 1 [1, 2, 3] == [2, 3]
drop 0 [1, 2, 3] == [1, 2, 3]
drop 10 [1, 2, 3] == []

maximum [1, 2, 3] == 3

minimum [1, 2, 3] == 1

sum [1, 2, 3] == 6

elem 1 [1, 2, 3] == True
1 `elem` [1, 2, 3] == True
elem 4 [1, 2, 3] == False

take 7 (cycle [1, 2, 3]) == [1, 2, 3, 1, 2, 3, 1]
take 3 (repeat 5) == [5, 5, 5]
take 3 [100..] == [100,101,102]

replicate 3 5 == [5, 5, 5]

zip [1,2,3] [5,6,7] == [(1,5),(2,6),(3,7)]


=====================================================
list comprehension
=====================================================
[x*2 | x <- [1..3]] == [2, 4, 6]
[x*2 | x <- [1..3], x*2 < 5] == [2, 4]
[x | x <- [1..5], x /= 3, x /= 4] == [1, 2, 5]
[(x, y) | x <- [1..5], y <- [7..8], x /= 3, x /= 4] == [(1,7),(1,8),(2,7),(2,8),(5,7),(5,8)]
[let xx = x*x in xx | x <- [1..5]] == [1,4,9,16,25]


=====================================================
char/string
=====================================================
Prelude> :t 'a'
'a' :: Char

Prelude> :t "a"
"a" :: [Char]

['a', 'b'] == "ab"


=====================================================
tuples
=====================================================
(1, "ab")
fst (1, "ab")
snd (1, "ab")
(1, 'a', ['a', 'b'], "abc", ["ab", "cd"])


=====================================================
lambda functions
=====================================================
f = \x -> x * x


=====================================================
($) function application
=====================================================
($) :: (a -> b) -> a -> b  
f $ x = f x

succ $ min 4 10 == succ (min 4 10)


=====================================================
(.) function composition
=====================================================
(.) :: (b -> c) -> (a -> b) -> a -> c  
f . g = \x -> f (g x)

(f . g . h) x  ==  f (g (h x))
map (negate . succ) [1, 2, 3] == map (\x -> negate(succ x)) [1, 2, 3]


=====================================================
pattern matching
=====================================================
isOne :: (Integral a) => a -> String
isOne 1 = "yes"
isOne _ = "no"

addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)
addVectors v1 v2 = (fst v1 + fst v2, snd v1 + snd v2)
addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)

first :: (a, b, c) -> a  
first (x, _, _) = x

first' :: (Show a) => [a] -> a
first' (x:xs) = x


=====================================================
patterns
=====================================================
first'' :: String -> String
first'' all@(x:xs) = "first of '" ++ all ++ "' is: " ++ show x


=====================================================
guards
=====================================================
isOne' :: (Integral a) => a -> Bool
isOne' x
  | x == 1 = True
  | otherwise = False

stupidAdd :: (Integral a) => a -> a -> a
x `stupidAdd` y
  | addThem < 10 = addThem
  | otherwise = addThem
  where addThem = x + y


=====================================================
where binding
=====================================================
syntactic construct to bind to variables at the end of a function
whole function can see them, also guards

isOne'' :: (Integral a) => a -> String
isOne'' x = answer
            where answer = if x == 1 then "yes" else "no"


=====================================================
let binding
=====================================================
let  in 

cylinderVol :: (RealFloat a) => a -> a -> a
cylinderVol r h =
  let side = 2 * pi * r * h
      top = pi * r ^2
  in  side + 2 * top

main = do
  putStrLn . show $ (let a = 4; b = 5 in a+b)


=====================================================
case expressions
=====================================================
case expression of pattern -> result  
                   pattern -> result  
                   pattern -> result  
                   ...  

myHead :: [a] -> a  
myHead [] = error "no head"  
myHead (x:_) = x  

myHead :: [a] -> a  
myHead xs = case xs of
              [] -> error "no head"  
              (x:_) -> x


=====================================================
record syntax
=====================================================
data                   =  | 
data   =  |  

data Person = Person { name :: String  
                     , age :: Int  
                     } deriving (Eq, Show)

main = do
  putStrLn . show $ Person {name="Peter", age=22}

generated functions:
name :: Person -> String
age :: Person -> Int

change value:

main = do
  peter <- return Person {name="Peter", age=22}
  peter <- return $ peter {age = 23}


=====================================================
type synonyms
=====================================================
type Person = [(String,String)]


=====================================================
Data.List
=====================================================
intersperse      intercalate      transpose
foldl            foldr            concat
concatMap        and              or
any              all              iterate
splitAt          takeWhile        dropWhile
span             break            sort
group            inits            tails
isInfixOf        isPrefixOf       isSuffixOf
alem             notElem          partition
find             elemIndex        elemIndices
findIndex        findIndices      zip3, zip4
zipWith3,        zipWith4         lines      unlines
words            unwords          nub
delete           \\               union
intersect       insert            length
take            drop              splitAt
!!              replicate         sort
insert          maximum           minimum


=====================================================
Data.Char
=====================================================
isControl      isSpace        isLower
isUpper        isAlpha        isAlphaNum
isPrint        isDigit        isOctDigit
isHexDigit     isLetter       isMark
isNumber       isPunctuation  isSymbol
isSeparator    isAscii        isLatin1
isAsciiUpper   isAsciiLower   toUpper
toLower        toTitle        digitToInt
intToDigit     ord      


=====================================================
Data.Map
=====================================================
fromList    empty         insert
null        size          singleton
lookup      member        map
filter      toList        keys
elems       fromListWith  insertWith


=====================================================
Data.Set
=====================================================
fromList    intersection  difference
union       null          size
member      empty         singleton
insert      delete        map
filter      toList      


=====================================================
common typeclasses
=====================================================
Eq
Ord
Show
Read
Enum
Bounded
Num
Integral
Floating




No comments: