You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
In functional programming, recursion replaces loops as the primary mechanism for repetition. Since FP discourages mutable state (no loop counters that change), recursive functions call themselves with modified arguments until a base case is reached.
Recursion occurs when a function calls itself. Every recursive function needs:
The factorial of n (written n!) is:
Haskell:
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)
factorial 5 -- 5 * 4 * 3 * 2 * 1 * 1 = 120
Python:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
factorial(5) # 120
factorial 5
= 5 * factorial 4
= 5 * (4 * factorial 3)
= 5 * (4 * (3 * factorial 2))
= 5 * (4 * (3 * (2 * factorial 1)))
= 5 * (4 * (3 * (2 * (1 * factorial 0))))
= 5 * (4 * (3 * (2 * (1 * 1))))
= 5 * (4 * (3 * (2 * 1)))
= 5 * (4 * (3 * 2))
= 5 * (4 * 6)
= 5 * 24
= 120
In imperative programming, you might write:
# Imperative loop
result = 1
for i in range(1, 6):
result *= i
This uses a mutable variable (result) that changes each iteration. In pure functional programming, variables cannot be reassigned, so recursion is used instead.
| Feature | Loops (Imperative) | Recursion (Functional) |
|---|---|---|
| State management | Mutable counter and accumulator | Arguments carry state |
| Termination | Loop condition | Base case |
| Side effects | Variable mutation | None (pure recursion) |
sumList :: [Int] -> Int
sumList [] = 0 -- base case: empty list
sumList (x:xs) = x + sumList xs -- recursive case: head + sum of tail
sumList [1, 2, 3, 4, 5] -- 15
lengthList :: [a] -> Int
lengthList [] = 0
lengthList (_:xs) = 1 + lengthList xs
lengthList [10, 20, 30] -- 3
fibonacci :: Int -> Int
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n = fibonacci (n - 1) + fibonacci (n - 2)
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.