fold.implicit: the machine keeps the work still to do, in its frames
def count(m):
if m[0] == "Note": return 1
return count(m[1]) + count(m[2])explicit: the program keeps it, in a stack of its own
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 nthe body of the loop is an argument, f
let rec fold f acc = function
| [] -> acc
| x :: xs -> fold f (f acc x) xs
let sum = fold (fun acc x -> acc + x) 0each branch is wrapped in a function
let 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))We use functions as values to answer how a program itself can control, step by step, a traversal of its data, possibly infinite, and its own computation: computing a value only when it is needed.
| the question | the function is | |
|---|---|---|
| Block 1 | Iterators: who drives the traversal? | one step of a traversal |
| Block 2 | Thunks and streams: when is a value computed? | a computation not yet run |
Warm-up. Questions on paper, then exercises in OCaml, on blocks 1 and 2.
Lab. Making a mini text editor, on a library that we write in three parts; the third goes with session 6.
| 1 | Closures | We start with what a function value is: a function with its environment, which can keep a state between two calls. |
| 2 | Traversing a list | First, we traverse a list by giving it a function, which it calls on every element (the list pushes the elements: internal iteration). |
| 3 | Stopping | Problem: in a strict language, the answer of this function cannot stop the traversal before the last element. |
| 4 | Iterators | Second, we traverse by asking for one element at a time (we pull the elements: external iteration). Using closures, the iterator remembers where it is in the list between two calls. |
| 5 | Generators | We let the language write the iterator: we write a function with yield, and the language makes the object that remembers where the function stopped. |
let add n x = x + n
let add3 = add 3
add3 10 (* 13 *)
The definition of add names two arguments, and we give it one, 3. What is add3?
add3fun x -> x + nn = 3Lab 4's evaluator builds this value for every function:
| Closure of string * term * env
add is curried: it takes n and returns a function. add 3 is a partial application.* The name and the construction are Landin's (1964): the function is closed by its environment.
let add n = fun x -> x + n
let add3 = add 3
add3 10 (* 13 *)
The call add 3 returns fun x -> x + n. Later, the
call add3 10 still finds n = 3: the function carries it.
add3fun x -> x + nn = 3Lab 4's evaluator builds this value for every function:
| Closure of string * term * env
add is curried: it takes n and returns a function. add 3 is a partial application.* The name and the construction are Landin's (1964): the function is closed by its environment.
var
The loop makes three functions. We call them after the loop. What does the program print?
var i: one variable for the whole loop
In OCaml, the one variable is a ref
OCamllet fs = ref [] and i = ref 0
let () =
while !i < 3 do
fs := (fun () -> !i) :: !fs;
incr i
done
List.rev_map (fun f -> f ()) !fs
[3; 3; 3]
var i makes one variable. The three functions keep that same variable.i = 3, and each function reads 3.let
The same program, with let in the place of var. What does it print?
let i: one variable per round of the loop
In OCaml, for makes a new i at every round
OCamllet fs = ref []
let () =
for i = 0 to 2 do
fs := (fun () -> i) :: !fs
done
List.rev_map (fun f -> f ()) !fs
[0; 1; 2]
let i makes a new variable at every round of the loop. Each function keeps its own.let there are three variables, and none of them changes.Here the closures read their variable. What if a closure changes it?
let counter () =
let n = ref 0 in
fun () -> incr n; !n
let a = counter ()
let b = counter ()
(* a (), then a (), then b () *)
1 2 1
Every call of counter makes a new variable n: a and b do not share it.
n itself, and no other code can read it or change it: a state of its own.
Javaclass Counter {
private int n = 0;
int tick() { return ++n; }
void reset() { n = 0; }
}
Counter c = new Counter();
c.tick(); c.tick(); c.reset();
System.out.println(c.tick());
1
Sources: Leroy 2026, §3.3. Objects add to this the choice of the method at run time and inheritance: Cook 2009.
JavaList<String> words = List.of("to", "be", "or", "not");
words.forEach(w ->
System.out.print(w + " "));
to be or not
Iterator<String> it = words.iterator();
while (it.hasNext()) {
String w = it.next();
System.out.print(w + " ");
}
to be or not
OCamllet words = ["to"; "be"; "or"; "not"]
List.iter
(fun w -> print_string (w ^ " "))
words
to be or not
let rec print = function
| [] -> ()
| w :: rest ->
print_string (w ^ " ");
print rest
to be or not
Does the list push each element into our function, or do we pull each element out of the list?
let rec fold_left f acc = function
| [] -> acc
| x :: xs -> fold_left f (f acc x) xs
From the first element to the last, with an accumulator.
let rec fold_right f xs z =
match xs with
| [] -> z
| x :: xs -> f x (fold_right f xs z)
Every :: is replaced by a call of f, and [] by z.
f once per element. The recursion is written once, in the fold; we pass f and write no recursion.map, filter and length, written with fold_rightOCamllet map f l = fold_right (fun x r -> f x :: r) l []
let filter p l = fold_right (fun x r -> if p x then x :: r else r) l []
let length l = fold_right (fun _ n -> n + 1) l 0
let text = ['h'; 'i'; '\n'; 'y'; 'o']
map Char.uppercase_ascii text
filter (fun c -> c <> '\n') text
length text
['H'; 'I'; '\n'; 'Y'; 'O'] ['h'; 'i'; 'y'; 'o'] 5
With fold_left, f x :: r puts each element in front of those met before it: the list is reversed.
let iter f l = fold_left (fun () x -> f x) () l
We call iter once and pass it a function. iter calls the function: it decides when, and how many times.
| OCaml | List.iter f xs |
| JavaScript | xs.forEach(f) |
| Java | xs.forEach(f) |
* Johnson & Foote 1988; the name is discussed in Fowler 2005. The pattern: Gamma et al. 1994, Iterator.
OCamllet text = ['h'; 'i'; '\n'; 'y'; 'o']
let visited = ref 0
let exists p l =
fold_left (fun found x ->
incr visited;
found || p x)
false l
exists (fun c -> c = '\n') text
exists is one more fold. The function we pass is a closure: it uses visited and p.
The newline is the third element. What is !visited at the end?
found=true visited=5
filter needed every element. exists has its answer at the third one.
type 'b go = Continue of 'b | Stop of 'b
let rec fold_until f acc = function
| [] -> acc
| x :: xs ->
match f acc x with
| Stop a -> a
| Continue a -> fold_until f a xs
OCamllet () = visited := 0
let exists p l =
fold_until (fun _ x ->
incr visited;
if p x then Stop true
else Continue false)
false l
found=true visited=3
Stop or Continue, and the loop reads it.*fold_until calls it, and we do not choose when. In part 4 we call next, which settles both: we ask when we want, and we stop by not asking.* After fold_until in OCaml's Base library. An exception also leaves a traversal: session 6.
interface Iterator<T> {
boolean hasNext();
T next();
}
We ask the list for an iterator, once. We call next: we decide when, and how many times.
Source: Gamma et al. 1994, Iterator. Java: java.util.Iterator, java.lang.Iterable.
JavaIterator<Character> it = text.iterator();
while (it.hasNext() && !found) {
visited++;
found = it.next() == '\n';
}
found=true visited=3
The loop is ours. Between two calls of next the traversal waits, and we may stop asking.
for (char c : text) { ... }
The for over a collection is this loop, written by the compiler: it calls iterator, then hasNext and next.
Javaclass ListIterator<T>
implements Iterator<T> {
private Node<T> here;
ListIterator(Node<T> l) { here = l; }
public boolean hasNext() {
return here != null;
}
public T next() {
if (here == null)
throw new NoSuchElementException();
T x = here.value();
here = here.next();
return x;
}
}
OCamllet iterator l =
let here = ref l in
fun () ->
match !here with
| [] -> None
| x :: rest ->
here := rest;
Some x
to be or not None
here. It is the counter of slide 10: a closure with a state.What do the three calls of next answer?
yield gives one element and suspends the function. The next call of next resumes it after that yield.
The answer has two fields: value, the element, and done, which is true when the function has ended.
function* two() {
yield 'h';
yield 'i';
}
Each yield is one case: it writes in pc where to resume, and returns the element.
After the last yield, done is true.
| pull: the consumer asks | push: the producer calls | |
|---|---|---|
| many values | an iterator: we call next | a function passed to iter: it is called once per element |
| one value | block 2 | session 6 |
In pull, the collection gives us an iterator and we call it. In push, we give the collection a function and it calls it.
Source: Meijer 2010, Subject/Observer is dual to Iterator; the table follows the Rx design notes.
| the question | the answer | |
|---|---|---|
| 1 | What does a function value carry? | Its code and its environment: a closure. |
| 2 | How do we visit every element of a list? | We pass a function to a fold: internal iteration. |
| 3 | Can our function stop the traversal? | By its answer, only with fold_until: Continue or Stop. |
| 4 | How can the consumer choose the next step? | It calls next: external iteration. |
| 5 | How can the producer remember where it stopped? | With yield: a generator, which the language suspends. |