ZetCode

F# recursion

last modified December 2, 2026

In this article we write recursive functions in F#.

A recursive function calls itself. It solves a problem by reducing it to a smaller problem of the same kind, until it reaches a case simple enough to answer directly, the base case. In functional languages, recursion replaces many of the loops of imperative code. F# makes recursion explicit: a function may only call itself when it is declared with let rec.

A function that calls itself

The factorial of n is the product of the numbers from 1 to n. It can be defined recursively: the factorial of 0 and 1 is 1, and the factorial of n is n times the factorial of n - 1.

factorial.fsx
let rec factorial n =
    if n <= 1 then 1
    else n * factorial (n - 1)

for i in 0..6 do
    printfn "%d! = %d" i (factorial i)

The definition translates directly to code.

let rec factorial n =
    if n <= 1 then 1
    else n * factorial (n - 1)

The rec keyword makes the name factorial visible inside its own body. The first branch is the base case; the second makes the recursive call with a smaller argument, so the recursion always ends.

λ dotnet fsi factorial.fsx
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

Forgetting rec

Without rec, the name of a function is not defined in its own body.

norec.fsx
let factorial n =
    if n <= 1 then 1
    else n * factorial (n - 1)

printfn "%d" (factorial 5)

This is the same function without the rec keyword. The compiler reports that factorial is not defined. The rule is deliberate: it makes recursion visible, and it allows a new definition to use an older binding of the same name.

λ dotnet fsi norec.fsx
norec.fsx(3,14): error FS0039: The value or constructor 'factorial' is not defined.

Recursion on numbers

Many functions on integers peel off one digit or one step at a time.

digits.fsx
let rec sumDigits n =
    if n < 10 then n
    else n % 10 + sumDigits (n / 10)

let rec countDigits n =
    if n < 10 then 1
    else 1 + countDigits (n / 10)

let rec power b e =
    if e = 0 then 1L
    else b * power b (e - 1)

printfn "sumDigits 98765 = %d" (sumDigits 98765)
printfn "countDigits 98765 = %d" (countDigits 98765)
printfn "power 2L 40 = %d" (power 2L 40)
printfn "power 7L 3 = %d" (power 7L 3)

We sum and count the digits of a number and compute integer powers.

let rec sumDigits n =
    if n < 10 then n
    else n % 10 + sumDigits (n / 10)

n % 10 is the last digit and n / 10 the rest of the number. A one-digit number is the base case.

let rec power b e =
    if e = 0 then 1L
    else b * power b (e - 1)

The power is computed with int64 values, because 240 does not fit into an int. The exponent shrinks by one in each call.

λ dotnet fsi digits.fsx
sumDigits 98765 = 35
countDigits 98765 = 5
power 2L 40 = 1099511627776
power 7L 3 = 343

Recursion on lists

A list is either empty, or it has a head, the first element, and a tail, the rest of the list. Recursive functions follow this shape: they handle the empty list as the base case and otherwise process the head and recurse on the tail.

lists.fsx
let rec sum xs =
    match xs with
    | [] -> 0
    | head :: tail -> head + sum tail

let rec count xs =
    match xs with
    | [] -> 0
    | _ :: tail -> 1 + count tail

let rec largest xs =
    match xs with
    | [] -> 0
    | [x] -> x
    | head :: tail -> max head (largest tail)

let rec doubleAll xs =
    match xs with
    | [] -> []
    | head :: tail -> head * 2 :: doubleAll tail

let values = [4; 9; 2; 15; 7]

printfn "sum: %d" (sum values)
printfn "count: %d" (count values)
printfn "largest: %d" (largest values)
printfn "doubled: %A" (doubleAll values)

We compute the sum, the length and the largest element of a list, and double all its elements.

let rec sum xs =
    match xs with
    | [] -> 0
    | head :: tail -> head + sum tail

The head :: tail pattern splits a non-empty list into its first element and the rest; see F# match expression.

let rec largest xs =
    match xs with
    | [] -> 0
    | [x] -> x
    | head :: tail -> max head (largest tail)

The pattern [x] matches a list with one element, which is its own largest element. The patterns are tried from top to bottom.

| head :: tail -> head * 2 :: doubleAll tail

doubleAll builds a new list: the :: operator puts the doubled head in front of the doubled tail. The functions of the List module, such as List.sum and List.map, are written this way.

λ dotnet fsi lists.fsx
sum: 37
count: 5
largest: 15
doubled: [8; 18; 4; 30; 14]

Accumulators and tail calls

Every function call takes a frame on the call stack, and the frame is kept until the call returns. In sumTo below, the addition happens after the recursive call returns, so all frames stay on the stack. If the recursive call is the last thing a function does, the call is a tail call, and F# reuses the frame. To get there, the partial result is passed along in an extra parameter, the accumulator.

accumulator.fsx
let rec sumTo n =
    if n = 0 then 0L
    else int64 n + sumTo (n - 1)

let rec sumToAcc n acc =
    if n = 0 then acc
    else sumToAcc (n - 1) (acc + int64 n)

printfn "sumTo 100 = %d" (sumTo 100)
printfn "sumToAcc 100 = %d" (sumToAcc 100 0L)
printfn "sumToAcc 10000000 = %d" (sumToAcc 10_000_000 0L)

let factorial n =
    let rec loop i acc =
        if i > n then acc
        else loop (i + 1) (acc * bigint i)
    loop 1 1I

printfn "25! = %A" (factorial 25)

We sum numbers with and without an accumulator, and compute a factorial with an inner helper function.

let rec sumToAcc n acc =
    if n = 0 then acc
    else sumToAcc (n - 1) (acc + int64 n)

The addition is done before the call, and the result of the recursive call is returned as it is. The function is tail recursive, and it sums ten million numbers without growing the stack.

let factorial n =
    let rec loop i acc =
        if i > n then acc
        else loop (i + 1) (acc * bigint i)
    loop 1 1I

The accumulator is an implementation detail, so it is hidden in a local function. The outer function is not recursive and has a clean signature. The factorial uses bigint, because 25! does not fit into any fixed-size integer.

λ dotnet fsi accumulator.fsx
sumTo 100 = 5050
sumToAcc 100 = 5050
sumToAcc 10000000 = 50000005000000
25! = 15511210043330985984000000

The limits

The call stack has a fixed size, set by the operating system and the .NET runtime. A recursion that is not a tail call and goes too deep fills it.

overflow.fsx
let rec sumTo n =
    if n = 0 then 0L
    else int64 n + sumTo (n - 1)

printfn "%d" (sumTo 10_000_000)

We call the sumTo function without an accumulator for ten million numbers. The program is stopped with a stack overflow, which cannot be caught or handled. The output below shows the first four lines of the report; it continues with the frames of F# Interactive.

λ dotnet fsi overflow.fsx
Stack overflow.
Repeated 261172 times:
--------------------------------
   at FSI_0001.sumTo(Int32)

The cost of naive recursion

The Fibonacci numbers start with 0 and 1, and each next number is the sum of the two before it. The direct recursive definition makes two recursive calls, which repeat the same work many times.

fibonacci.fsx
let rec fib n =
    if n < 2 then n
    else fib (n - 1) + fib (n - 2)

let fibFast n =
    let rec loop i a b =
        if i = n then a
        else loop (i + 1) b (a + b)
    loop 0 0L 1L

for i in 0..10 do
    printf "%d " (fib i)
printfn ""

let sw = System.Diagnostics.Stopwatch.StartNew()
let slow = fib 35
let slowTime = sw.ElapsedMilliseconds

sw.Restart()
let fast = fibFast 35
let fastTime = sw.ElapsedMilliseconds

printfn "fib 35 = %d in %d ms" slow slowTime
printfn "fibFast 35 = %d in %d ms" fast fastTime
printfn "fibFast 90 = %d" (fibFast 90)

We compare the direct definition with a version that carries the last two numbers in accumulators.

let rec fib n =
    if n < 2 then n
    else fib (n - 1) + fib (n - 2)

fib 35 calls fib 33 twice, fib 32 three times, and so on; the number of calls grows exponentially, to almost thirty million for fib 35.

let fibFast n =
    let rec loop i a b =
        if i = n then a
        else loop (i + 1) b (a + b)
    loop 0 0L 1L

The fast version moves along the sequence once, so it needs n steps. It is tail recursive and works with int64, which holds Fibonacci numbers up to the 92nd. The Stopwatch measures the times, which differ from run to run and between computers.

λ dotnet fsi fibonacci.fsx
0 1 1 2 3 5 8 13 21 34 55 
fib 35 = 9227465 in 70 ms
fibFast 35 = 9227465 in 0 ms
fibFast 90 = 2880067194370816120

Mutual recursion

Two functions are mutually recursive when they call each other. Since a function can only use names defined above it, F# joins such functions with the and keyword.

mutual.fsx
let rec isEven n =
    if n = 0 then true
    else isOdd (n - 1)

and isOdd n =
    if n = 0 then false
    else isEven (n - 1)

for n in [0; 7; 10; 13] do
    printfn "%d: even %b, odd %b" n (isEven n) (isOdd n)

We decide whether a number is even or odd by counting down.

let rec isEven n =
    if n = 0 then true
    else isOdd (n - 1)

and isOdd n =
    if n = 0 then false
    else isEven (n - 1)

A number is even when its predecessor is odd, and odd when its predecessor is even. let rec ... and ... defines both functions at once, so each can see the other. The example shows the technique; the % operator is the practical way to test parity.

λ dotnet fsi mutual.fsx
0: even true, odd false
7: even false, odd true
10: even true, odd false
13: even false, odd true

Euclid's algorithm and fast powers

Some algorithms are naturally recursive. Euclid's algorithm finds the greatest common divisor of two numbers: the gcd of a and b is the gcd of b and the remainder of a divided by b.

gcd.fsx
let rec gcd a b =
    if b = 0 then a
    else gcd b (a % b)

let lcm a b = a / gcd a b * b

let rec fastPower b e =
    if e = 0 then 1L
    elif e % 2 = 0 then
        let half = fastPower b (e / 2)
        half * half
    else b * fastPower b (e - 1)

printfn "gcd 1071 462 = %d" (gcd 1071 462)
printfn "gcd 17 5 = %d" (gcd 17 5)
printfn "lcm 4 6 = %d" (lcm 4 6)
printfn "fastPower 3L 39 = %d" (fastPower 3L 39)

We compute greatest common divisors, a least common multiple, and a power by repeated squaring.

let rec gcd a b =
    if b = 0 then a
    else gcd b (a % b)

The remainder gets smaller in each step, and when it reaches zero, the other number is the result. The recursive call is a tail call.

elif e % 2 = 0 then
    let half = fastPower b (e / 2)
    half * half

For an even exponent, be is the square of be/2. Halving the exponent needs only about log2 e steps, against e steps for the power function above.

λ dotnet fsi gcd.fsx
gcd 1071 462 = 21
gcd 17 5 = 1
lcm 4 6 = 12
fastPower 3L 39 = 4052555153018976267

Towers of Hanoi

In the Towers of Hanoi puzzle, a stack of disks of different sizes is moved from one peg to another, one disk at a time, never putting a larger disk on a smaller one. A third peg serves as a spare.

hanoi.fsx
let rec hanoi n source target spare =
    if n > 0 then
        hanoi (n - 1) source spare target
        printfn "move disk %d from %c to %c" n source target
        hanoi (n - 1) spare target source

hanoi 3 'A' 'C' 'B'

The recursive solution moves the top n - 1 disks to the spare peg, moves the largest disk to the target, and then moves the n - 1 disks from the spare peg onto it. The function returns unit; the if without else does nothing when there are no disks to move. Three disks need seven moves; in general, n disks need 2n - 1.

λ dotnet fsi hanoi.fsx
move disk 1 from A to C
move disk 2 from A to B
move disk 1 from C to B
move disk 3 from A to C
move disk 1 from B to A
move disk 2 from B to C
move disk 1 from A to C

Recursion on strings

A string can be processed like a list: handle the first character and recurse on the rest.

reverse.fsx
let rec reverse (s: string) =
    if s.Length <= 1 then s
    else reverse s[1..] + string s[0]

let rec isPalindrome (s: string) =
    if s.Length <= 1 then true
    elif s[0] <> s[s.Length - 1] then false
    else isPalindrome s[1 .. s.Length - 2]

printfn "%s" (reverse "falcon")
printfn "%s" (reverse "recursion")

for w in ["level"; "rotor"; "river"; "racecar"] do
    printfn "%s: %b" w (isPalindrome w)

We reverse strings and check palindromes.

let rec reverse (s: string) =
    if s.Length <= 1 then s
    else reverse s[1..] + string s[0]

s[1..] is a slice: the string from the second character to the end. The reversed rest is followed by the first character.

let rec isPalindrome (s: string) =
    if s.Length <= 1 then true
    elif s[0] <> s[s.Length - 1] then false
    else isPalindrome s[1 .. s.Length - 2]

A word is a palindrome when its first and last characters are equal and the part between them is a palindrome. Each slice creates a new string, so these functions are fine for words, but for long texts the string functions of .NET are faster.

λ dotnet fsi reverse.fsx
noclaf
noisrucer
level: true
rotor: true
river: false
racecar: true

Source

F# language reference: Recursive Functions: The rec Keyword

In this article we have written recursive functions on numbers, lists and strings, made them tail recursive with accumulators, and defined mutually recursive functions. Functions are introduced in F# functions, list patterns in F# match expression, and the List module in F# list.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.