Functions are the main tool
In Haskell, functions are not just one feature among many: they are what you build almost everything from. A function can be stored in a list, passed as an argument, returned as a result, or created on the fly. Small functions are snapped together into larger ones the way you connect pipes.
This lesson teaches the three skills that make that comfortable.
- Pattern matching: defining a function by cases, one equation per shape of input, with the compiler checking that you covered them all.
- Currying: the fact that every Haskell function really takes one argument at a time, which makes "give it some of its arguments now and the rest later" free.
- Composition: joining functions end to end with
., so that a data pipeline reads as one line.
The vocabulary
Definition— Function application
You apply a function by writing its arguments after it, separated by spaces: max 3 7. Application binds more tightly than any operator, so f x + 1 means (f x) + 1, and f (x + 1) needs the parentheses.
Definition— Pattern
A pattern describes a shape a value may have and names its parts. Patterns include literals (0, "yes"), variables (n, which matches anything and names it), the wildcard _ (matches anything, names nothing), tuples (x, y), the empty list [], a non-empty list x : xs (a first element x and the rest xs), and fixed-length lists [a, b]. A function's equations are tried from top to bottom, and the first whose patterns match is used.
Definition— Guard
A guard is a boolean condition, written after |, that must also hold for an equation to apply. otherwise is simply another name for True, used as the last, catch-all guard.
Definition— Currying and partial application
A function of "two arguments" such as max :: Int -> Int -> Int is really a function that takes one Int and returns a function that takes the other. The arrow associates to the right: Int -> Int -> Int means Int -> (Int -> Int). Supplying only some arguments, max 3, is partial application, and it gives you a new function. This style is named currying, after Haskell Curry.
Definition— Section
A section is an operator with one side filled in, in parentheses: (* 2) doubles, (2 ^) raises 2 to a power, (> 3) tests whether a number exceeds 3. The side you leave empty is where the argument goes.
Definition— Composition and application operators
f . g is the function that applies g and then f: (f . g) x = f (g x). f $ x is just f x, but $ has the lowest precedence of all operators, so it saves parentheses: print $ sum xs is print (sum xs).
Patterns, guards and case
Defining functions by cases
-- Guards: conditions tried from top to bottom.
isLeapYear :: Int -> Bool
isLeapYear y
| y `mod` 400 == 0 = True
| y `mod` 100 == 0 = False
| otherwise = y `mod` 4 == 0
-- Patterns on literals, with a catch-all at the end.
weekday :: Int -> String
weekday 1 = "Monday"
weekday 6 = "Saturday"
weekday 7 = "Sunday"
weekday n
| n >= 2 && n <= 5 = "a weekday"
| otherwise = "not a day"
-- Patterns on lists: the order of the equations matters.
joinNames :: [String] -> String
joinNames [] = "nobody"
joinNames [a] = a
joinNames [a, b] = a ++ " and " ++ b
joinNames (a : rest) = a ++ ", " ++ joinNames rest
main :: IO ()
main = do
print (map isLeapYear [1900, 2000, 2024, 2026])
putStrLn (weekday 6 ++ "; " ++ weekday 3 ++ "; " ++ weekday 9)
putStrLn (joinNames [])
putStrLn (joinNames ["Ana"])
putStrLn (joinNames ["Ana", "Kofi"])
putStrLn (joinNames ["Ana", "Kofi", "Mei", "Ravi"])[False,True,True,False]
Saturday; a weekday; not a day
nobody
Ana
Ana and Kofi
Ana, Kofi, Mei and RaviEach function shows a different way to split a problem into cases.
isLeapYear uses guards. The Gregorian rule has exceptions to exceptions (every 4th year, but not every 100th, but every 400th), and guards let you write the rules in exactly that order, most specific first. Reading the guards top to bottom reads the rule aloud.
weekday mixes literal patterns with a final equation whose pattern is a plain variable, n, that matches any number. The final equation then uses guards of its own. If we had put weekday n first, it would match everything, and the special days would never be reached.
joinNames matches on the shape of a list. [] is the empty list, [a] a list of exactly one element, [a, b] exactly two, and a : rest any non-empty list, with a its first element and rest the remainder. The colon is the list constructor: "Ana" : ["Kofi", "Mei"] is ["Ana", "Kofi", "Mei"]. The last equation calls joinNames on a shorter list, which is recursion; it ends because every call removes an element until one of the shorter patterns matches. Trace joinNames ["Ana", "Kofi", "Mei", "Ravi"]: it becomes "Ana, " ++ joinNames ["Kofi", "Mei", "Ravi"], then "Ana, Kofi, " ++ joinNames ["Mei", "Ravi"], where the two-element equation gives "Mei and Ravi".
case, accumulators and as-patterns
-- case: match an expression against patterns, anywhere.
respond :: String -> String
respond input = case words input of
[] -> "Say something."
["hello"] -> "Hello to you too."
["add", a, b] -> a ++ " + " ++ b ++ " = " ++ show (read a + read b :: Int)
"echo" : rest -> unwords rest
_ -> "Sorry, I don't understand " ++ show input
-- Recursion with an accumulator, hidden in a local helper called go.
collatzSteps :: Int -> Int
collatzSteps = go 0
where
go steps 1 = steps
go steps n
| even n = go (steps + 1) (n `div` 2)
| otherwise = go (steps + 1) (3 * n + 1)
-- An as-pattern, rest@(...), names a part of the value while matching inside it.
squeeze :: String -> String
squeeze (a : rest@(b : _))
| a == b = squeeze rest
| otherwise = a : squeeze rest
squeeze short = short
main :: IO ()
main = do
mapM_ (putStrLn . respond) ["hello", "add 19 23", "echo ni hao", "", "dance"]
print (map collatzSteps [1, 6, 7, 27])
putStrLn (squeeze "bookkeeper")Hello to you too.
19 + 23 = 42
ni hao
Say something.
Sorry, I don't understand "dance"
[0,8,16,111]
bokepercase expr of matches any expression, not just a function's arguments, against a list of patterns. Here we split the input into words and match the resulting list: a list of one particular word, a list of three words whose first is "add", a list starting with "echo", or anything else (_). This is a tiny command interpreter in a few lines, and it is the shape of many real ones.
collatzSteps counts how many steps the Collatz process (halve even numbers, map odd n to 3n + 1) takes to reach 1. The counting is done by a local function, conventionally called go, which carries the count so far as an extra argument, an accumulator. Notice that collatzSteps itself has no argument in its definition: collatzSteps = go 0 says "collatzSteps is go with its first argument already set to 0", a partial application. Recursion is how Haskell loops, and because the recursive call to go is the last thing each equation does (a tail call), GHC compiles it into a loop that uses no extra stack.
squeeze removes repeated neighbouring letters. Its first pattern needs at least two elements, a and b, but we also want to recurse on the list starting at b. Writing rest@(b : _) gives that sublist a name, rest, while still matching inside it. Lists shorter than two elements fall through to the second equation and are returned unchanged.
Currying, sections and composition
One argument at a time
Ask GHCi for a few types:
ghci> :t (+)
(+) :: Num a => a -> a -> a
ghci> :t (+) 3
(+) 3 :: Num a => a -> a
ghci> :t map (*2)
map (*2) :: Num b => [b] -> [b]
ghci> :t (.)
(.) :: (b -> c) -> (a -> b) -> a -> cWriting an operator in parentheses, (+), turns it into an ordinary function name. Its type, a -> a -> a, reads as "takes an a and returns an a -> a". Give it one argument and you get exactly that: (+) 3 is the function that adds three. Likewise map (*2) is map with its function argument supplied; what remains is a function from lists to lists.
The type of (.) says: give me a function from b to c and a function from a to b, and I will give you a function from a to c. That is composition, read right to left like mathematics' f ∘ g.
Building functions from functions
import Data.Char (toUpper)
-- Add a percentage to a price. Two arguments... or one at a time.
addPercent :: Double -> Double -> Double
addPercent pct price = price + price * pct / 100
main :: IO ()
main = do
let withVat = addPercent 16 -- a new function, waiting for a price
print (withVat 80)
print (map (addPercent 10) [20, 35, 50])
print (map (* 2) [1, 2, 3], map (2 ^) [1, 2, 3], map (^ 2) [1, 2, 3])
print (filter (> 3) [5, 1, 4, 2], map (subtract 1) [10, 20])
let shout = map toUpper . filter (/= ' ')
putStrLn (shout "hakuna matata")
print (sum . map (^ 2) . filter odd $ [1 .. 10])
print ((\x y -> 10 * x + y) 4 2)92.8
[22.0,38.5,55.0]
([2,4,6],[2,4,8],[1,4,9])
([5,4],[9,19])
HAKUNAMATATA
165
42addPercent 16is a function that adds 16 percent. Because the rate comes first and the price last, partial application gives something useful. Haskell programmers order parameters with this in mind: the argument that varies most goes last.(* 2)and(^ 2)put the argument on the left (x * 2,x ^ 2), while(2 ^)puts it on the right (2 ^ x). One trap:(- 1)is not a section but the number minus one, so Haskell providessubtract 1instead.shoutis built by composition without ever naming its argument: first remove spaces, then make every letter upper case. Code written this way, as a pipeline of functions with no named argument, is called point-free style.sum . map (^ 2) . filter odd $ [1 .. 10]reads right to left: keep the odd numbers, square them, add them up.$separates the pipeline from its input; without it,.would try to compose with a list.\x y -> 10 * x + yis a lambda, an anonymous function. The backslash is meant to look like the Greek letter λ.
Note
Point-free style is elegant in short pipelines and unreadable when overdone. A useful rule from professional code review: if a reader has to work out what the arguments are, name them. average xs = sum xs / fromIntegral (length xs) is clearer than any point-free version of it. The linter HLint, covered in lesson 10, suggests point-free rewrites only where they are simple.
Note
where and guards work well together because a where clause scopes over all the guards of its equation. In a definition like bmiCategory w h | bmi < 18.5 = "under" | bmi < 25 = "normal" | otherwise = "over" where bmi = w / h ^ 2, the helper value bmi is defined once and used by every guard. A let ... in could not do that, because it is an expression inside a single branch. This is the most common reason Haskell programmers reach for where.
How professionals use patterns
Pattern matching is more than a convenient switch. Because the compiler knows every shape a type can take, it can tell you when you forgot one. Compile joinNames without its [] equation with the -Wall flag, and GHC warns that the patterns are not exhaustive and names the missing case, []. Without -Wall, GHC 9.14 compiles silently, and the program crashes with "Non-exhaustive patterns" if it ever receives an empty list. Every professional Haskell project turns on -Wall (usually in the project's .cabal file), and many treat warnings as errors in continuous integration.
That is also why experienced Haskell programmers avoid partial functions, functions that crash on some inputs, such as head, which fails on an empty list. Since GHC 9.8, using head or tail triggers a warning (-Wx-partial) that suggests pattern matching instead. You will see in lesson 5 how types such as Maybe make the "no answer" case explicit, so the compiler can check you handled it.
A few points of style that you will see everywhere:
- Write a type signature above every top-level function.
- Put the base cases (
[],0, the special values) first and the general recursive case last. - Prefer guards to nested
ifs, andcasewhen you match on the result of a computation. - Name a recursive helper
go, with any accumulators as its first arguments. - In practice, you will write explicit recursion less often than you might think: the next lesson shows how
map,filterand the folds capture the common recursion patterns once and for all.
Common misconceptions
Misconception
"f(x, y) calls f with two arguments." In Haskell it calls f with one argument, the pair (x, y). That is legal when f really takes a tuple, which is why the mistake can produce confusing type errors. Curried functions are called as f x y.
Misconception
"map f . filter g xs keeps the elements and maps them." Application binds tighter than ., so this parses as map f . (filter g xs), trying to compose a function with a list. Write map f . filter g $ xs, or map f (filter g xs).
Misconception
"The order of equations does not matter, as long as all cases are covered." Equations are tried top to bottom, and a general pattern placed early hides the specific ones after it. GHC warns about such unreachable equations ("Pattern match is redundant") when -Wall is on.
Misconception
"Recursion is slow and overflows the stack, so real programs need loops." A tail-recursive helper like go compiles to a loop. Non-tail recursion over large inputs can use a lot of memory in Haskell, but for a reason specific to laziness, covered in lesson 8, and the standard library functions in the next lesson handle the common cases efficiently.
Exercises
1. Functions, currying and pattern matching
Warm-upComputationalUsing the joinNames function from the lesson, what does this program print?
joinNames :: [String] -> String
joinNames [] = "nobody"
joinNames [a] = a
joinNames [a, b] = a ++ " and " ++ b
joinNames (a : rest) = a ++ ", " ++ joinNames rest
main :: IO ()
main = putStrLn (joinNames ["Ines", "Tariq", "Yuki"])
2. Functions, currying and pattern matching
Warm-upComputationalWhat does this program print?
main :: IO ()
main = print (((* 2) . (+ 1)) 20)
3. Functions, currying and pattern matching
CoreComputationalWhat does this program print?
main :: IO ()
main = print (map (`div` 2) [7, 10], map (12 `div`) [3, 4])
4. Functions, currying and pattern matching
CoreComputationalWhat does this program print?
digitSum :: Int -> Int
digitSum 0 = 0
digitSum n = n `mod` 10 + digitSum (n `div` 10)
main :: IO ()
main = print (digitSum 2026 * 2)
5. Functions, currying and pattern matching
CoreComputationalWhich definition returns "zero" for sign 0, "negative" for sign (-4) and "positive" for sign 9?
6. Functions, currying and pattern matching
CoreComputationalWhich of these expressions mean the same as sum (map (* 3) (filter even xs))? Choose all that apply.
7. Functions, currying and pattern matching
StretchHumanGiven between :: Int -> Int -> Int -> Bool, where between lo hi x tests whether x lies from lo to hi, what is the type of between 1 10?
Further reading and resources
- Haskell 2010 Language Report, section 3.17: Pattern MatchingThe formal rules for how patterns match, in order, from left to right.
- GHC User's Guide: Warnings and sanity-checkingWhat -Wall turns on, including the incomplete-patterns warning.
- HoogleSearch for functions by type, for example (a -> b) -> [a] -> [b].