Programming Paradigms Session 5 · Wed 30 September 2026

← all sessions

Session 5

Functions as Values: Iterators and Streams

Iterators, thunks and streams: two uses of a function passed as a value.

Lecture

1IteratorsPDFSlides →

The two decks and their PDFs are a first version, published on the day of the lecture: their content might change.

Lab

This session

Session 5 is about functions passed as values, and how a program uses them to control, step by step, a traversal of its data and its own computation:

  • two styles of iteration, internal and external,
  • delayed evaluation: thunks, sequences computed on demand, memoisation.

The lecture, in two blocks

1Iterators: who drives the traversal? Closures and what they capture; map, filter and length written with a fold; internal iteration (the list calls our function) and how to stop it before the last element; external iteration (we ask for the next element); an iterator written by hand in Java and in OCaml; a generator in JavaScript, and the object that the compiler makes of it.
2Thunks and streams: when is a value computed? A thunk is a function that holds a computation not yet run. With thunks we choose when a value is computed; with sequences (streams), how far a list is computed, and it can be without end; with memoisation, that a value is computed at most once. Each time we make the choice ourselves in OCaml, then look at Haskell, where the language makes it. An appendix to read at home is on memoising a function.

A third block, on continuations, was announced for this session and was not given. What it was to give is the appendix of session 6’s second block, as reading; Part C of the quest is optional and rests on it.

The examples of the lecture are on lists and sequences. In the quest we write a mini text editor on a rope, the tree structure in which text editors store a document.

The questions of the session

Each part of the lecture asks one question. The two conclusions answer them.

Block 1: a function carries out one step of a traversal. Who calls it?

The questionThe answer
What does a function value carry? Its code and its environment: a closure.
How do we visit every element of a list? We pass a function to a fold: internal iteration.
Can our function stop the traversal? By its answer, only with fold_until: Continue or Stop.
How can the consumer choose the next step? It calls next: external iteration.
How can the producer remember where it stopped? With yield: a generator, which the language suspends.

Block 2: a function holds a computation not yet run. When do we run it?

The questionThe program decides, in OCamlThe language decides, in Haskell
When is a value computed? When we call the thunk that holds it.When it is used.
How far is a sequence computed? As far as we ask: a sequence.Every list is a sequence.
How many times? Once, if we keep the result: lazy.Once: every value is lazy, by default.

In block 2 the function has type unit -> 'a: we call it to get a value. In session 6 a function holds the rest of the computation, 'a -> 'r: we call it to give a value.

The types of the session

Session 3 introduced algebraic data types on the melody: a closed list of shapes, each value built in exactly one way, taken apart by match, with the compiler telling us when a case is missing. In session 5 we wrote more of them, each a few lines long. They add three things to the melody:

  • a parameter, 'a: one type for a rope of characters, a sequence of lines, a history of ropes;
  • constructors that carry a function: data and code in one value, which is this session’s subject;
  • a type that says when a value is computed.

An answer that is a choice: 'b go (block 1, lab A3)

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

The function we hand to fold_until answers with the accumulator in both cases; the constructor says what the fold does next. After Stop, the rest of the list is not visited. On the rope, in the lab, fold_until itself returns a 'b go, so that the left subtree can tell the right one that it stopped.

One list, three types (block 2)

type 'a list = [] | (::) of 'a * 'a list

type 'a node = Nil | Cons of 'a * 'a seq
and  'a seq = unit -> 'a node            (* a sequence: the rest is a thunk *)

type 'a node = Nil | Cons of 'a * 'a seq
and  'a seq = 'a node Lazy.t             (* the rest is a lazy value *)
The rest has typeIt isIt is computed
'a lista valuebefore we read the first element
unit -> 'a nodea thunkeach time we call it
'a node Lazy.ta lazy valuethe first time we force it, then kept

The shape is the same in the three: an empty case, and a case with one element and the rest. Only the type of the rest changes, and with it when the rest is computed. To compute the first 25 Fibonacci numbers, fibs makes 196 392 additions when the rest is a thunk, and 23 when it is a lazy value. The second declaration is recursive through a function type: node and seq are defined together, with and.

A lazy value, made by hand: 'a state (block 2)

type 'a state =
  | Delayed of (unit -> 'a)
  | Value of 'a

let delay f = ref (Delayed f)

let force s = match !s with
  | Value v -> v
  | Delayed f ->
      let v = f () in
      s := Value v;
      v

The two constructors are the two moments of a lazy value: before it is computed it holds a thunk, afterwards the value. force replaces the first by the second in the reference, so the thunk runs at most once. OCaml’s lazy does the same inside the language.

The lab: 'a rope and 'a history

type 'a rope =
  | Leaf of 'a
  | Cat of 'a rope * 'a rope

type 'a history = {
  past : 'a list;        (* the versions before the present one, the latest first *)
  present : 'a;
  future : 'a list;      (* the versions undone, the next one to redo first *)
}

A rope is a leaf, or two ropes put one after the other. The type has no constructor for an empty rope, so every rope has at least one leaf, and no function on ropes has an empty case to handle. A history is a record: a product, which holds its three fields at once, where a sum holds one constructor out of several. A version of the document is the root of a rope, so undo and redo move roots from one list to the other and copy no text.

A value that may be missing: 'a option

In the lab, find_first returns None when no leaf satisfies the predicate. In the appendix, memo asks its table with Hashtbl.find_opt and matches on Some y and None. The type makes the caller say what happens when there is no value.

We wrote the types; the compiler found the types of the functions. How it finds them, and what a type with a parameter means, is session 11.

The lab: warm-up, then the editor

WWarm-up. Lists on paper, then Pascal’s triangle as a sequence at the keyboard. Its last part, lab 2’s queue with a lazy front, is the homework.
0The rope, on paper and in the toplevel. Drawing ropes, counting their nodes; count_notes on lab 3’s melody, read as a fold.
AOne step of a traversal (rope.ml). fold; insert and delete; undo and redo; fold_until; the rope as a sequence, and same, which compares two sequences element by element.
BA computation not yet run (stream.ml). take, map, filter, take_while on sequences; the lines of a document; grep.
CThe rest of the computation (next.ml). Goes with session 6, on continuations: we do it after that lecture.

Nothing is handed in; the checks, dune exec ./main.exe, say which levels remain.

Homework

  • Reading. CS3110, section 9.4, sequences, with 9.4.4 on laziness: the lab’s 'a seq, and the library’s Seq. Leroy, Control structures in programming languages (2026), chapter 4, sections 4.1 and 4.2: iterators and generators, block 1 in more languages. Its chapters 6 and 7, on continuations, go with session 6.
  • Finish the lab, parts 0, A and B, in order; the stretches are on the lab page.
  • The warm-up’s last part. Lab 2’s queue, whose front is a lazy value: question E on the sheet, exercise 11 in warmup/queue.ml. A check counts the reversals when one version is popped twice.
  • The appendix of block 2. Memoising a function: memo, memo_rec, and the two exercises on its last slide.

Languages this session

LanguageRole
OCamlread in both blocks, write in the lab — the first types with a parameter that we write ourselves
Javaread two traversals of a list, an iterator written by hand
JavaScriptread closures made in a loop, a generator and the object the compiler makes of it
Haskellread lists without end: the natural numbers, the primes, the Fibonacci numbers

Further reading

None of this is required.

Block 1

  • CS3110, chapter 4 — section 4.4, fold, and section 4.7, currying. map, filter and the two folds, in the OCaml of the lab.
  • Peter Landin, “The mechanical evaluation of expressions” — The Computer Journal, 1964. Where the closure gets its name: a function together with the environment that closes it.
  • MDN, “Iterators and generators” — the guide. The protocol behind next and for…of, and function*.

Block 2

  • John Hughes, “Why functional programming matters” — 1989 (PDF). Lazy evaluation as a way to glue programs together: one part produces a list without end, another decides how much of it to read.
  • Abelson and Sussman, Structure and Interpretation of Computer Programs — section 3.5, streams. delay and force in Scheme, and the same memoisation as our 'a state.
  • Melissa O’Neill, “The genuine sieve of Eratosthenes” — Journal of Functional Programming, 2009 (PDF). The two lines of Haskell on the slides test each number against every smaller prime; Eratosthenes crosses out multiples. The paper measures the difference and writes the real sieve on a list without end.
  • CS3110, section 9.5, memoization. The appendix of block 2, with a table, in OCaml.
  • Chris Okasaki, Purely Functional Data Structures (1998), chapters 4 and 6. Streams with lazy values, and the banker’s queue: lab 2’s queue, paid once with lazy. The book is not free; the thesis it grew from (CMU, 1996, PDF) is, and has the same material in its chapters 2 and 3.

The lab and the types