The two previous sessions were about data structures:
| S2 | how data are modified: persistent and ephemeral data structures |
| S3 | how data are constructed: algebraic data types and objects |
| S4, S5 | paradigms of how algorithms run |
Who, and how, decides the next step of a computation? Four parts, four questions:
The λ-calculus: the smallest language that computes everything, its evaluation strategies, and booleans, numbers, if and recursion built from three forms.
An evaluator for the calculus, in OCaml: terms as a type, substitution, two strategies, closures. The same program grows a type checker in session 10.
Two answers, both from 1936:
| a processor executing instructions and changing the state, step-by-step, using a transition function | Turing |
| a calculus transforming a program, according to a rewriting relation, to evaluate a function applied to its arguments | Church |
| imperative/functional style | a global state, changed by assignment and sequencing (von Neumann 1945) | expressions and application, no state (Lisp 1958, ML 1973) |
| machine/calculus model | an operational model of how — the tool of complexity theory | an equational model of what — the foundation of language semantics (Landin 1964, Scott 1970, Plotkin 1975) |
| explicit/implicit control | the order of the steps is written: ";", loops, the program counter | the order is not written: a strategy chooses — this session |
| state | reads | writes | moves | next |
|---|---|---|---|---|
| go | 1 | 1 | → | go |
| go | ␣ | 1 | ← | back |
| back | 1 | 1 | ← | back |
| back | ␣ | ␣ | → | halt |
A machine that adds one to a number written in unary.
Terms are built from three forms:
xλx. tt uOne rule: an application is replaced by the function's body, with the argument put in for the variable. A term can offer two places to apply it:
(λx. x + x) (2 × 3)
argument first ↙ ↘ function first
(λx. x + x) 6 (2 × 3) + (2 × 3)
↓ ↓
6 + 6 6 + (2 × 3)
↓ ↓
12 6 + 6 → 12
Numbers, + and × are not part of the calculus; they keep this first example readable. Block 2 defines numbers from the three forms.
| the machine | the calculus | |
|---|---|---|
| built, 1945 / 1958 | the stored-program computer (von Neumann) | Lisp (McCarthy) |
| control | a program counter and a stack | substitution + a choice of what to reduce |
| constructs | ; while x := e (and many others) | just function definition and application |
| the default in | C, Java, Python, JavaScript | Haskell, OCaml, Scheme, Erlang |
Paradigm ≠ language: Java has lambdas, OCaml has for. A language makes one of the two the default.
int sum(int *a, int n) {
if (n == 0) return 0;
return a[0] + sum(a + 1, n - 1);
}
sum calls itself before it can add. The machine must remember, for every call not yet finished three things:
a, n3 + _One such record is a frame. Frames are pushed at a call and popped at a return: the call stack.
Pythondef sum_list(xs):
if not xs:
return 0
return xs[0] + sum_list(xs[1:])
print(sum_list(list(range(100))))
print(sum_list(list(range(10_000))))
4950
Traceback (most recent call last):
File "recursion_limit.py", line 4, in sum_list
return xs[0] + sum_list(xs[1:])
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
| language | the stack ends at* |
|---|---|
| Python | 1 000 frames, by a counter — a deliberate choice |
| Java | StackOverflowError after 33 436 frames here |
| C | 8 MB (ulimit -s): a segmentation fault |
| OCaml 5 | the stack lives on the heap and grows: 1 GB |
*One measurement; concrete numbers might differ.
A tree 100 000 notes deep. Right: session 2's stack in a new job — Lab 2's maze visit was this loop.
def count(m):
n, stack = 0, [m]
while stack:
m = stack.pop()
if m[0] == "Note": n += 1
else: stack += [m[2], m[1]]
return n
let rec sum acc = function
| [] -> acc
| x :: xs -> sum (acc + x) xs
sum 0 [3; 1; 4] (* 8 *)
After the call, nothing is left to do: no pending 3 + _. The accumulator carries what the stack would have held.
let sum xs =
let acc = ref 0 and l = ref xs in
while !l <> [] do
acc := !acc + List.hd !l;
l := List.tl !l
done; !acc
The compiled code of the left is the right: the frame is reused, the call becomes a jump.
* A tail call is a call in the position where its result is returned unchanged.
| guaranteed | not guaranteed |
|---|---|
| Scheme — central to the original 1975 design; required by every standard since | Python — refused on purpose: the traceback would lose frames |
Haskell, Erlang — iteration is normally written this way; OCaml optimises it, and also has for and while | Java — the JVM has no tail-call instruction |
| Lua, Elixir | C — an optimisation the compiler may or may not apply |
| loop → recursion | Every loop can be written as a tail-recursive function: the loop variables become its arguments. |
| recursion → loop | Every recursion can be written as a loop with an explicit stack: the stack holds the pending work. |
Sources: recursion elimination — Bird 1977; the construction — Reynolds 1972; a tail call as a jump — Steele 1977.
let rec sum = function
| [] -> 0
| x :: xs -> x + sum xslet rec product = function
| [] -> 1
| x :: xs -> x * product xslet rec length = function
| [] -> 0
| x :: xs -> 1 + length xsThree functions, one recursion. What differs: the value for [], and how x is combined with the result for the rest.
If the two differences were arguments, one function would do for all three.
foldlet rec fold f acc = function
| [] -> acc
| x :: xs -> fold f (f acc x) xs
let sum = fold (fun acc x -> acc + x) 0
let length = fold (fun acc _ -> acc + 1) 0
The loop is now a value: the recursion is written once, in fold; a use writes no control at all — we pass it, name it, return it.
A function that takes or returns a function is higher-order; functions are first-class values.
let compose f g = fun x -> f (g x) (* takes two functions, returns one *)
let evens_squared = compose (List.map square) (List.filter even)Session 3’s sets-as-objects (Way 2) were already this: a set was a function, and insert returned one.
Session 5: who drives a loop — the collection (fold) or the caller (iterators, generators) — and control as a value the program passes: closures, thunks, continuations.
Next: how fold runs, step by step.
f is appliedlet rec fold_left f acc = function
| [] -> acc
| x :: xs -> fold_left f (f acc x) xs
f runs as soon as an element is met, from the left, and its result is carried along as acc.
The recursive call is the last thing done — a tail call, like sum acc on Does a tail call need the stack?. The frame is reused: a loop, no stack.
let rec fold_right f xs z = match xs with
| [] -> z
| x :: xs -> f x (fold_right f xs z)
f runs only after the rest of the list is done, so the first application to run is the last element's — from the right.
The recursive call is inside f x _: not a tail call. One pending frame per element — the stack of The same call, in the calculus.
f: left to right with a carried value, or right to left with pending work.f, same list — two answers?With f = (+), z = 0:
fold_left: ((0 + 3) + 1) + 4 = 8
fold_right: 3 + (1 + (4 + 0)) = 8
The same result: addition does not care where the parentheses go.
With f = (−), z = 0:
fold_left: ((0 − 3) − 1) − 4 = −8
fold_right: 3 − (1 − (4 − 0)) = 6
Two results: subtraction does care.
f is part of the meaning — unless f is associative and the seed is its identity: then only the parenthesisation changes. Session 9 makes that the condition for running a fold in parallel.Algorithm = Logic + Control (Kowalski, 1979), read off the code: f and z are the logic, fold_left or fold_right the control. With + the control changes only the cost; with − it changes the answer.
fold as a rewriting of the list’s treeA list is a tree of (:) nodes ending in []. fold_right f xs z replaces every (:) by a call to f and [] by z — same shape; fold_left f z xs builds the mirrored tree from z upwards.
| language | the sum of a list | and its friends |
|---|---|---|
| OCaml | List.fold_left (+) 0 xs | List.map, List.filter |
| Python | functools.reduce(operator.add, xs, 0) | map, filter, comprehensions |
| JavaScript | xs.reduce((acc, x) => acc + x, 0) | .map, .filter |
| Java | xs.stream().reduce(0, Integer::sum) | .map, .filter |
map applies a function to every element; filter keeps the elements a function accepts. Both are folds.
Session 5: who drives this loop — the collection or the caller — and what else a loop can be.
OCamllet f a b = a + b;;
f (print_string "first "; 10)
(print_string "second "; 20);;
second first - : int = 30
OCaml: right to left — and the manual says unspecified.
JavaScript: left to right, by the standard. C: unspecified.
A second question, different from the order: whether an argument is evaluated before the call at all.
| mode | the argument is evaluated | languages |
|---|---|---|
| call by value | before the call, once | C, Java, Python, JavaScript, OCaml, Scheme |
| call by name | at each use; never if unused | Algol 60 (its default); Scala, parameters written x: => T |
| call by need | at first use, once; never if unused | Haskell (everywhere); R (every argument is a promise); Scala lazy val |
if be a function?A test of call by value: write if as an ordinary function.
OCamllet my_if c t e = if c then t else e
let rec fact n =
my_if (n = 0) 1 (n * fact (n - 1))
Stack overflow during evaluation (looping recursion?).
Under call-by-value the arguments are evaluated before the call — fact (n - 1) too, even when n = 0, which recurses forever. In such a language if cannot be an ordinary function: it must not evaluate its branches before choosing. So if is a keyword.
if be a function? — with the branches as functionsOCamllet my_if c t e = if c then t () else e ()
let rec fact n =
my_if (n = 0)
(fun () -> 1)
(fun () -> n * fact (n - 1))
- : int = 120
A function's body is not evaluated until the function is called. Each branch is now a function of no argument; my_if calls only the one it chose, and the other is never run.
if can be a function — if the caller delays the branches by hand. Block 2 gives this a name, and shows the language doing it instead.| the question | the answer | |
|---|---|---|
| 1 | What is computing? | Two definitions, 1936. In the machine the next step is a function of the state; in the calculus it is a relation, and a strategy makes it a function. |
| 2 | What does a machine need to call a function? | A frame. The stack holds what the calculus keeps in the term. Every loop can be written as a tail-recursive function, every recursion as a loop with a stack. |
| 3 | Do we need a loop construct at all? | No. The recursion is written once, in fold; a use passes the body and writes no control. fold_left and fold_right differ in the order of applying f. |
| 4 | In which order, and when, are arguments evaluated? | The language decides both: the order (fixed or unspecified) and the mode — by value, by name, by need. Under call by value if cannot be a function unless the caller delays the branches. |
fold rather than a loop, a function that delays rather than an argument evaluated first. Block 2 formalises these choices in a minimal setting of the functional paradigm: the λ-calculus.