Haskell Basics: Functions and Pattern Matching

Haskell functions are defined by equations — you state what the output is for each input pattern.

Function definitions

HASKELL
-- Simple function
double :: Int -> Int
double x = x * 2

-- Multiple arguments
add :: Int -> Int -> Int
add a b = a + b

Pattern matching

HASKELL
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)

-- Pattern matching on tuples
swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)

Lists

HASKELL
-- Lists are homogeneous (all elements same type)
numbers :: [Int]
numbers = [1, 2, 3, 4, 5]

-- Cons operator (:) prepends
moreNumbers = 0 : numbers  -- [0, 1, 2, 3, 4, 5]

-- List comprehensions
evens = [x | x <- [1..20], even x]  -- [2, 4, 6, ..., 20]
pairs = [(x, y) | x <- [1..3], y <- [1..3]]  -- [(1,1),(1,2),...,(3,3)]

-- Useful functions
head [1, 2, 3]      -- 1
tail [1, 2, 3]      -- [2, 3]
length [1, 2, 3]    -- 3
null []              -- True
reverse [1, 2, 3]   -- [3, 2, 1]
take 2 [1, 2, 3]    -- [1, 2]
drop 2 [1, 2, 3]    -- [3]
elem 2 [1, 2, 3]    -- True

Higher-order functions

HASKELL
-- map applies a function to every element
map (*2) [1, 2, 3]     -- [2, 4, 6]

-- filter keeps elements matching a predicate
filter even [1..10]    -- [2, 4, 6, 8, 10]

-- foldl/foldr reduce a list to a single value
foldl (+) 0 [1, 2, 3]  -- 6
foldr (+) 0 [1, 2, 3]  -- 6

-- Composition
doubleAndFilter = filter even . map (*2)
doubleAndFilter [1, 2, 3]  -- [4, 6]

Lambda functions

HASKELL
addOne = \x -> x + 1
add = \a b -> a + b

map (\x -> x * x) [1, 2, 3]  -- [1, 4, 9]

Tips

  • Haskell uses indentation for block structure (like Python).
  • Use : (cons) to build lists: 1 : [2, 3] = [1, 2, 3].
  • Function composition (.) is the primary way to combine functions.
  • Pattern matching replaces if/else chains.

Next: types.