Haskell Quick Reference
Functions & Types
-- Type signatures
add :: Int -> Int -> Int
add x y = x + y
-- Function composition
transform :: [String] -> [String]
transform = filter (not . null) . map (map toUpper)
-- Lambda
double = \x -> x * 2
evens = filter (\x -> x `mod` 2 == 0) [1..10]
Pattern Matching
-- List patterns
head' :: [a] -> a
head' [] = error "empty list"
head' (x:_) = x
-- Factorial
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
-- Guards
classify :: Int -> String
classify n
| n < 0 = "negative"
| n == 0 = "zero"
| n < 10 = "small"
| otherwise = "large"
Data Types
-- Algebraic Data Type (ADT)
data Shape = Circle Double
| Rectangle Double Double
| Triangle Double Double Double
area :: Shape -> Double
area (Circle r) = pi * r * r
area (Rectangle w h) = w * h
area (Triangle a b c) = ...
-- Record syntax
data Person = Person { name :: String, age :: Int }
alice = Person { name = "Alice", age = 28 }
olderAlice = alice { age = 29 } -- update
Maybe Monad
-- Maybe for safe computation
safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv x y = Just (x `div` y)
-- do notation
compute :: Int -> Int -> Maybe Int
compute x y = do
a <- safeDiv x y
b <- safeDiv a 2
return (a + b)
-- fmap and >>=
fmap (*2) (Just 5) -- Just 10
Just 5 >>= safeDiv 10 -- Just 2
Nothing >>= safeDiv 10 -- Nothing