Efficiency

Tail recursion, stack and heap, continuations

ITT8060 Advanced Programming · Autumn 2026

Tallinn University of Technology

Full prose version with runnable examples: notes.html

ITT8060

Two questions

In Lecture 2 we wrote e ~> e' for the evaluation relation.

Today we think about the cost of evaluation.

Time: how many steps does it take?

Space: how much memory is needed?

Plan: cost, accumulating parameters, tail calls, stack and heap, trees, continuations.

ITT8060

1 · Cost

ITT8060
let rec fact n =
  if n = 0 then
    1
  else
    n * fact (n - 1)
fact 5
~> 5 * fact (5 - 1)
~> 5 * fact 4
~> 5 * (4 * fact 3)
~> 5 * (4 * (3 * fact 2))
~> 5 * (4 * (3 * (2 * fact 1)))
~> 5 * (4 * (3 * (2 * (1 * fact 0))))
~> 5 * (4 * (3 * (2 * (1 * 1))))
~> ...
~> 120

Factorial

In the step case we leave the current n "behind".

While we evaluate fact (n - 1), we need to "remember" that we still have to multiply the result with n.

How many values of n must be remembered?

Time and space (asymptotically) proportional to n.

ITT8060

Memory is finite

Remembering a value means storing it somewhere. Eventually we will run out of space.

> fact 1_000_000;;
Stack overflow.
Repeated 261410 times:
--------------------------------
   at FSI_0002.fact(Int32)
--------------------------------

(The int result would have wrapped around long before. Beside the point: the evaluation never finishes.)

ITT8060
let rec naiveRev xs =
  match xs with
  | [] -> []
  | x :: xs' -> naiveRev xs' @ [x]
naiveRev [1; 2; 3; 4; 5]
~> naiveRev [2; 3; 4; 5] @ [1]
~> (naiveRev [3; 4; 5] @ [2]) @ [1]
~> ((naiveRev [4; 5] @ [3]) @ [2]) @ [1]
~> ...
~> (((([] @ [5]) @ [4]) @ [3]) @ [2]) @ [1]
~> ((([5] @ [4]) @ [3]) @ [2]) @ [1]
~> (([5; 4] @ [3]) @ [2]) @ [1]
~> ([5; 4; 3] @ [2]) @ [1]
~> [5; 4; 3; 2] @ [1]
~> [5; 4; 3; 2; 1]

Naive reversal

In the base case, we have five pending @ operations and we have remembered five singleton lists.

Space proportional to length \(n\).

Lecture 4: xs @ ys takes steps proportional to the length of xs.

One @ per element, and its first argument grows every time: \(0 + 1 + \cdots + (n - 1) = n(n - 1)/2\) steps.

Time proportional to \(n^2\).

ITT8060
let rec fact' n =
  if n = 0 then
    1
  else
    let n' = n - 1
    let rr = fact' n'
    let r  = n * rr
    r

let rec naiveRev' xs =
  match xs with
  | [] -> []
  | x :: xs' ->
      let rr = naiveRev' xs'
      let ys = [x]
      let r  = rr @ ys
      r

Factorial and reverse again

The same functions with every intermediate value bound to a name.

rr is the recursive result and it is needed to compute the result r.

ITT8060

2 · Accumulating parameters

ITT8060

A more general problem

The pending operation in fact is multiplication by n (i.e., n * _).

To not leave "behind" pending operations we solve a more general problem: we compute the factorial of n multiplied with "something". Specification:

factA n acc = acc * fact n

Here acc is an accumulating parameter.

The original problem is the special case where acc = 1:

fact n = 1 * fact n = factA n 1
ITT8060

Factorial using accumulators

When n = 0, as fact 0 = 1, we have:

factA 0 acc = acc * fact 0   // specification
            = acc * 1        // def. of fact
            = acc            // simplify

When n > 0, as fact n = n * fact (n - 1), we have:

factA n acc = acc * fact n              // specification
            = acc * (n * fact (n - 1))  // def. of fact
            = (acc * n) * fact (n - 1)  // * is associative
            = factA (n - 1) (acc * n)   // specification

The last step is the key: (acc * n) * fact (n - 1) is something that we can compute with factA. We have a recursive definition.

ITT8060
let rec factA n acc =
  if n = 0 then
    acc
  else
    factA (n - 1) (acc * n)

let factorial n = factA n 1
factA 5 1
~> factA (5 - 1) (1 * 5)
~> factA 4 5
~> factA 3 20
~> factA 2 60
~> factA 1 120
~> factA 0 120
~> 120

factA

val factA: n: int -> acc: int -> int

No pending multiplications.

The result of factA 0 120 is the result of factA 5 1.

fact 3: 3 * (2 * (1 * 1)).

factA 3 1: ((1 * 3) * 2) * 1.

ITT8060
let rec revA xs acc =
  match xs with
  | [] -> acc
  | x :: xs' -> revA xs' (x :: acc)

let reverse xs = revA xs []
revA [1; 2; 3] []
~> revA [2; 3] (1 :: [])
~> revA [3] [2; 1]
~> revA [] [3; 2; 1]
~> [3; 2; 1]

revA

val revA:
  xs: 'a list -> acc: 'a list -> 'a list

What is revA [1; 2; 3] []?

[3; 2; 1]. One :: per element, no @ at all: time proportional to the length, nothing pending.

Space proportional to the length (list, accumulator).

Compare with reverse defined using fold from Lecture 4.

ITT8060

3 · Tail recursion

ITT8060

Tail positions and tail recursion

A function call is in tail position when its result is returned as the result (with no further computation).

A function is tail recursive if every recursive call in its definition is in tail position.

Example: in the expression g x (x + f y) the function g is applied in tail position; f is not as further computation depends on its result.

Where in the body e of let rec f x = e are the tail positions?

let y = e1 in y           those of e1
let y = e1 in e2          those of e2             (not e1)
if b then e1 else e2      those of e1 and e2      (not b)
match ... | p1 -> e1 ...  those of e1, ..., en    (not the scrutinee)
g e                       the application itself  (not e)
e1; e2                    those of e2             (not e1)
ITT8060
let rec countdown n =
  if n = 0 then
    0
  else
    countdown (n - 1)

let rec sumTo n =
  if n = 0 then
    0
  else
    n + sumTo (n - 1)

let rec dropNeg xs =
  match xs with
  | [] -> []
  | x :: xs' ->
      if x < 0 then
        dropNeg xs'
      else
        x :: dropNeg xs'

Spot the tail call (I)

Which of these are tail recursive?

countdown: yes, tail position of a branch.

sumTo: no, sumTo (n - 1) is an argument to +.

dropNeg: no, the first call is a tail call but the second is an argument to ::.

ITT8060
let rec lastOf xs =
  match xs with
  | [] -> failwith "empty list"
  | [x] -> x
  | _ :: xs' -> let r = lastOf xs' in r

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

Spot the tail call (II)

lastOf: yes (no further computation after recursive call).

sumA: yes.

ITT8060

Two examples

let rec even n =
  match n with
  | 0 -> true
  | 1 -> false
  | n -> even (n - 2)
let rec badA n acc =
  if n = 0 then
    acc
  else
    n * badA (n - 1) (n * acc)

Accumulators are not necessary for tail recursion: even is tail recursive.

badA is not tail recursive although it does have a parameter named acc.

ITT8060

Tail call elimination/optimisation

Recall: the result of a tail call is returned without any further (local) computation.

Nothing in the caller's stack frame is needed anymore.

Compiler reuses the current stack frame for the callee instead of pushing a new stack frame.

That is why factA 1_000_000 1 returned while fact 1_000_000 overflowed. Reusing the current stack frame led to constant stack usage.

ITT8060
[<TailCall>]
let rec fact n =
  if n = 0 then 1
  else n * fact (n - 1)

$ dotnet build
Program.fs(4,12): warning FS3569:
The member or function 'fact' has the
'TailCallAttribute' attribute, but is
not being used in a tail recursive way.

Is it tail recursive?

Two tests.

First, factA handles a larger input in F# Interactive. factA 1_000_000 1?

0 (int overflows), but it returns.

Second: [<TailCall>] attribute in a compiled project.

F# Interactive does not report this warning.

ITT8060

Iterative functions

Tail recursive functions are sometimes also called iterative functions.

Starting from initial value x : X, iterate a function f : X -> X while a condition c : X -> bool evaluates to true on the current value, and then project the final result by applying p : X -> Y.

Example: factA iterates the function fun (n, acc) -> (n - 1, acc * n) while the following predicate fun (n, acc) -> n <> 0 evaluates to true, and then projects the result by snd.

(5, 1) ~> (4, 5) ~> (3, 20) ~> (2, 60) ~> (1, 120) ~> (0, 120) ~> 120

Imperatively:

let factW n =
  let mutable x = (n, 1)
  while (fun (n, acc) -> n <> 0) x do
    x <- (fun (n, acc) -> (n - 1, acc * n)) x
  snd x
ITT8060

4 · Stack and heap

ITT8060

Basic layout

Primitive values live on the stack; lists are cons cells on the heap (Lecture 3).

let xs = [5; 6; 7]
let ys = 3 :: 4 :: xs
let zs = xs @ ys
let n = 27

ys: two new cells, second points to xs. zs: @ copies the cells of xs, the last cell points to ys.

Lists are immutable and thus such reuse is safe.

ITT8060

Push

let ws =
  let us = [1; 2]
  let vs = [3; 4]
  us @ vs

Evaluating the let-expression pushes a new frame.

The frame has entries for the local us and vs, and an entry for the result.

ITT8060

Pop, and garbage

When the let-expression completes, sf1 is popped and ws receives the result.

The cells marked † are unreachable from the stack and thus are considered garbage. The garbage collector reclaims them behind the scenes.

Heap is separated into three generations by age. (Most objects die young.)

ITT8060

Memory during revA

One frame per call, as if no frame were reused (no TCO). To ease the visualisation we say that a frame consists of two pointers: xs and acc.

Each call on a nonempty list allocates a new cons cell (new accumulator).

Nothing in a frame is needed after the recursive call (we just return the result of the recursive call).

TCO: the compiler reuses the current frame for the recursive call.

ITT8060

Measurements (#time)

> let xs16 = List.replicate 1000000 16;;
> for i in xs16 do fact i |> ignore;;
Real: 00:00:00.035, CPU: 00:00:00.035,
GC gen0: 0, gen1: 0, gen2: 0
> for i in xs16 do factA i 1 |> ignore;;
Real: 00:00:00.014, CPU: 00:00:00.014,
GC gen0: 0, gen1: 0, gen2: 0
> for i in xs16 do ();;
Real: 00:00:00.007, CPU: 00:00:00.007,
GC gen0: 0, gen1: 0, gen2: 0
> let xs20000 = [1 .. 20000];;
> naiveRev xs20000;;
Real: 00:00:02.711, CPU: 00:00:04.034,
GC gen0: 185, gen1: 2, gen2: 1
> revA xs20000 [];;
Real: 00:00:00.001, CPU: 00:00:00.001,
GC gen0: 0, gen1: 0, gen2: 0

The loop alone costs 7 ms, so factA's gain is more than the visible factor.

Reversal: 2.7 seconds against 1 millisecond, and 188 garbage collections against none.

Not only is naiveRev quadratic, the way @ is used generates a lot of garbage.

ITT8060
> bigList 200_000 |> List.length;;
val it: int = 200000
> bigList 300_000;;
Stack overflow.
Repeated 261442 times:
   at FSI_0002.bigList(Int32)

> bigListA 10_000_000 [] |> List.length;;
val it: int = 10000000

(heap limited to 1 GB:)
> bigListA 100_000_000 [];;
System.OutOfMemoryException:
Exception of type
'System.OutOfMemoryException' was thrown.

The limits

let rec bigList n =
  if n = 0 then
    []
  else
    1 :: bigList (n - 1)

let rec bigListA n acc =
  if n = 0 then
    acc
  else
    bigListA (n - 1) (1 :: acc)

The stack: some \(2.6 \cdot 10^5\) frames. The heap: two orders of magnitude more cells here.

bigListA runs in one frame: the result list grows on the heap.

ITT8060

5 · Trees

ITT8060

From Lecture 6

type 'a BinTree =
  | Empty
  | Node of 'a BinTree * 'a * 'a BinTree

let rec size t =
  match t with
  | Empty -> 0
  | Node (l, _, r) -> size l + 1 + size r

Is size tail recursive?

No: both calls are arguments to +.

ITT8060

Accumulators with trees?

We can try to use accumulators:

let rec sizeA t acc =
  match t with
  | Empty -> acc
  | Node (l, _, r) -> sizeA r (sizeA l (acc + 1))

Is sizeA tail recursive?

No: sizeA l (acc + 1) is an argument to the outer recursive call.

Processing r first does not help.

ITT8060

6 · Continuation-passing style

ITT8060

The rest of the computation

What we need: recurse into l (with a tail call) and when l has been processed continue with r.

This extra piece of information (what to do after l has been processed? continue with r) must be a parameter to the function.

A continuation is a function that represents "the rest of the computation": what to do, later, with the result of the current computation.

With k : int -> int we describe how to get the final result from a partial result.

We pass k along as an argument; when the partial result n is known, we "run" k from n by k n.

ITT8060
let rec factK n k =
  match n with
  | 0 -> k 1
  | n -> factK (n - 1) (fun r -> k (n * r))
factK 3 k
~> factK 2 k3    // k3 = fun r -> k (3 * r)
~> factK 1 k2    // k2 = fun r -> k3 (2 * r)
~> factK 0 k1    // k1 = fun r -> k2 (1 * r)
~> k1 1
~> k2 (1 * 1)
~> k2 1
~> k3 (2 * 1)
~> k3 2
~> k (3 * 2)
~> k 6

factK

What is the type of factK?

val factK: n: int -> k: (int -> 'a) -> 'a

More general than the int -> int continuation we set out with.

factK 5 id? 120

Note that both factK and k, k_i are called in tail positions only; the pending multiplications sit inside the continuation, not on the stack.

ITT8060

sizeK

let rec sizeK t k =
  match t with
  | Empty -> k 0
  | Node (l, _, r) ->
      sizeK l <| fun sl ->
      sizeK r <| fun sr ->
      k (sl + 1 + sr)
val sizeK:
  t: 'a BinTree -> k: (int -> 'b) -> 'b
let size' t = sizeK t id

Once we have sl and sr we can run the original continuation k.

ITT8060
let rec spine n acc =
  if n = 0 then
    acc
  else
    spine (n - 1) (Node (acc, n, Empty))

let deep = spine 1_000_000 Empty
> size deep;;
Stack overflow.
Repeated 130707 times:
   at FSI_0003.size[...](BinTree`1<Int32>)
> sizeK deep id;;
val it: int = 1000000

Trading stack for heap

A left-leaning tree with a million nodes. size overflows the stack, sizeK computes the result.

The pending work has not disappeared: it is represented by the "growing" continuation on the heap.

Heap is larger but not free. On trees that fit the stack, size is faster.

ITT8060

Summary

Function calls consume stack; deep recursion may overflow the stack.

Tail call optimisation keeps stack usage bounded; we must be able to write functions tail recursively.

Sometimes helps: accumulating parameters.

General method: continuation-passing style.

To write performant code we must be aware of the representation of data in memory (stack and heap).

ITT8060

Homework and reading

Homework 6 is out this week.

Reading: Hansen & Rischel, Functional Programming Using F#, chapter 9, "Efficiency".

Exercises (iteration, tail-recursive list functions, continuations on trees): the Exercises section of notes.html.

ITT8060