Haskell Recursion
Haskell has no for or while loops. Since values never change, a loop counter couldn't be updated anyway. Instead, repetition is expressed with recursion: a function that calls itself on a smaller problem until it reaches a case it can answer directly.
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
main :: IO ()
main = do
print (factorial 5)
print (map factorial [0 .. 10])
print (factorial 30)120
[1,1,2,6,24,120,720,5040,40320,362880,3628800]
265252859812191058636308480000000
Every recursive function needs two parts:
- A base case that stops the recursion (
factorial 0 = 1). - A recursive case that moves toward the base case (
n - 1is smaller thann).
Here is how GHC unfolds factorial 4:
factorial 4
= 4 * factorial 3
= 4 * (3 * factorial 2)
= 4 * (3 * (2 * factorial 1))
= 4 * (3 * (2 * (1 * factorial 0)))
= 4 * (3 * (2 * (1 * 1)))
= 24Recursion on lists
Lists are recursive by nature: a list is empty, or an element followed by another list. So list functions follow the same template, one equation for [] and one for (x : xs). Here are hand-written versions of some Prelude functions:
mySum :: [Int] -> Int
mySum [] = 0
mySum (x : xs) = x + mySum xs
myLength :: [a] -> Int
myLength [] = 0
myLength (_ : xs) = 1 + myLength xs
myMap :: (a -> b) -> [a] -> [b]
myMap _ [] = []
myMap f (x : xs) = f x : myMap f xs
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter _ [] = []
myFilter keep (x : xs)
| keep x = x : myFilter keep xs
| otherwise = myFilter keep xs
main :: IO ()
main = do
print (mySum [1 .. 10])
print (myLength "recursion")
print (myMap (* 3) [1, 2, 3])
print (myFilter odd [1 .. 10])55
9
[3,6,9]
[1,3,5,7,9]
Once you see the pattern, you will notice it everywhere: "handle the empty list, then handle the head and recurse on the tail".
Several base cases and several arguments
Some problems need more than one base case, or recurse on two arguments at once:
fib :: Int -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
myZip :: [a] -> [b] -> [(a, b)]
myZip (x : xs) (y : ys) = (x, y) : myZip xs ys
myZip _ _ = []
myTake :: Int -> [a] -> [a]
myTake n _ | n <= 0 = []
myTake _ [] = []
myTake n (x : xs) = x : myTake (n - 1) xs
main :: IO ()
main = do
print (map fib [0 .. 12])
print (myZip [1, 2, 3] "ab")
print (myTake 3 "Haskell", myTake 10 [1, 2])[0,1,1,2,3,5,8,13,21,34,55,89,144]
[(1,'a'),(2,'b')]
("Has",[1,2])
Warning: This
fibis elegant but exponentially slow:fib 40repeats the same sub-calls billions of times. The laziness lesson shows a version that computesfib 100instantly.
Quicksort in five lines
Recursion makes divide-and-conquer algorithms very short. This is the famous (if not the fastest) Haskell quicksort: pick the first element as the pivot, sort the smaller and larger elements recursively, and put the pivot between them.
quicksort :: Ord a => [a] -> [a]
quicksort [] = []
quicksort (pivot : rest) =
quicksort smaller ++ [pivot] ++ quicksort larger
where
smaller = [x | x <- rest, x < pivot]
larger = [x | x <- rest, x >= pivot]
main :: IO ()
main = do
print (quicksort [38, 27, 43, 3, 9, 82, 10, 3])
print (quicksort "recursion")[3,3,9,10,27,38,43,82]
"ceinorrsu"
Accumulators and tail recursion
The mySum above builds up a chain of pending additions (1 + (2 + (3 + …))) before it can add anything. An alternative is to carry the running result in an extra argument, an accumulator. The recursive call is then the last thing the function does (a tail call), which GHC compiles into a loop:
sumTo :: Int -> Int
sumTo n = go 0 1
where
go !acc i
| i > n = acc
| otherwise = go (acc + i) (i + 1)
countDigits :: Integer -> Int
countDigits = go 1
where
go acc k
| k < 10 = acc
| otherwise = go (acc + 1) (k `div` 10)
main :: IO ()
main = do
print (sumTo 10)
print (sumTo 10000000)
print (countDigits 2026, countDigits (2 ^ 100))55
50000005000000
(4,31)
The helper is traditionally called go. The ! in !acc (a bang pattern, available by default in GHC2021) forces the accumulator to be computed at every step; without it, laziness could still pile up unevaluated acc + i expressions. The strictness lesson explains this in depth.
Tip: In everyday code you rarely write raw recursion. Most loops are a
map,filteror fold, which the next lessons cover. But every one of those is defined by exactly the recursion you saw here.
Test yourself
What happens if a recursive function has no reachable base case?
- GHC adds one automatically
- It returns 0
- It recurses forever (or until memory runs out)
- It is a syntax error
Which equation is the base case of myLength?
myLength (_ : xs) = 1 + myLength xsmyLength [] = 0- Both
- Neither
What is an accumulator in a recursive helper?
- A global variable
- An extra argument that carries the result built so far
- A type class
- A list of all previous calls