00 — how to use these
Three files, and a way to read them
rope.ml, stream.ml and next.ml are drop-in replacements for the files with the holes; copy them over ours and dune exec ./main.exe reports 55 passes, and the editor has every key and every panel. They carry the comments of the lab's own files and nothing more: the explanations are on this page, level by level, next to the code that they explain.
One thing to check before reading a solution: our own version passes the checks, or we know which check it fails and why. A function that passes the checks and differs from the one here is not wrong; the levels have several right answers, and the page says where.
01 — the rope, on paper
Six questions on the structure
Every value below was run in the toplevel, #use "rope.ml", on 2026-09-30.
0.1 — from a drawing to a value, and back
Cat (Cat (Leaf 'b', Leaf 'y'), Leaf '\n'): the text by and a newline. The other way, Cat (Leaf 'o', Cat (Leaf 'k', Leaf '\n')) is a root with o on the left and, on the right, a node with k and the newline: the text ok and a newline.
0.2 — how many nodes
n − 1, whatever the shape: every Cat joins two ropes into one, and a rope of n leaves is made from n ropes of one leaf by n − 1 joins. doc has 4, the rope of 0.1 has 2. With an empty rope, Cat (empty, r) would hold the text of r, so one document could have any number of nodes, and length could not be a fold with fun _ -> 1.
0.3 — the deepest and the shallowest
The deepest is a list: Cat (Leaf 'a', Cat (Leaf 'b', … Cat (Leaf 'g', Leaf 'h'))), depth 7. The shallowest is balanced, four nodes over four pairs, depth 3. of_string builds the balanced one: of_list cuts the list in the middle and builds each half. An editor prefers it because split (A1) walks one path from the root, so its cost is the depth.
0.4 — two equalities
iter print_char doc prints hi, a newline, yo. of_string "hi\nyo" = doc is true: five leaves cut in the middle give (h i) (\n (y o)), which is doc exactly. doc' = doc is false: the same text in another shape, and = compares the shapes. A5 writes the comparison that reads the leaves.
0.5 — sharing
One node, the Cat; a and b are not copied. l == a is true: the left child of d is a itself. d and d2 share a (match d, d2 with Cat (l, _), Cat (l2, _) -> l == l2 is true). Written as in the question, d2 builds its right half anew, three nodes (Cat, Leaf 'Y', Leaf 'o'), plus the root: four. On a string the change copies every character: six here, and every line of samples/long.txt there.
0.6 — count_notes, and what a fold is
let rec count_notes m = match m with
| Note _ -> 1
| Rest _ -> 0
| Seq (a, b) -> count_notes a + count_notes b
At a leaf, a function of the leaf (Note gives 1, Rest gives 0); at a Seq, a function of the two results, +. Those are the two arguments of fold. On the rope: fold (fun e -> match e with Note _ -> 1 | Rest _ -> 0) ( + ). Session 4 asked for this fold over the melody's tree; here it is.
02 — part A
One step of a traversal
A0 — fold, and three functions from it
let rec fold (leaf : 'a -> 'b) (cat : 'b -> 'b -> 'b) (r : 'a rope) : 'b =
match r with
| Leaf x -> leaf x
| Cat (l, r) ->
let a = fold leaf cat l in
let b = fold leaf cat r in
cat a b
let length (r : 'a rope) : int = fold (fun _ -> 1) ( + ) r
let depth (r : 'a rope) : int = fold (fun _ -> 0) (fun a b -> 1 + max a b) r
let to_list (r : 'a rope) : 'a list = fold (fun x -> [ x ]) ( @ ) r
One function per constructor, as session 3's thesis said of every function on a type with two shapes. The two let are not decoration: cat (fold leaf cat l) (fold leaf cat r) would be the same function, but OCaml evaluates the arguments of a call from right to left, so the right subtree would be visited first. The editor lights the leaves in the order they are visited, and the check fold visits the left subtree first hands over a cat that records the order.
length counts one per leaf and adds; depth is 0 at a leaf and one more than the deeper child; to_list makes a list of one element per leaf and appends. The last one is the slow way to flatten a rope, quadratic in the worst case, and it is what the editor uses until A4: leaves flattened on the status line is length of that list.
A1 — insert and delete
let insert (i : int) (x : 'a) (r : 'a rope) : 'a rope =
if i = 0 then Cat (Leaf x, r)
else if i = length r then Cat (r, Leaf x)
else
let l, rest = split i r in
Cat (l, Cat (Leaf x, rest))
let delete (i : int) (r : 'a rope) : 'a rope =
let n = length r in
if n < 2 || i < 0 || i >= n then invalid_arg "delete"
else if i = 0 then snd (split 1 r)
else if i = n - 1 then fst (split i r)
else
let l, rest = split i r in
let _, after = split 1 rest in
Cat (l, after)
split is given and does the work: it returns the first i leaves and the others, building new nodes only on the path it walks down. The two ends need a case of their own because split is defined for 0 < i < length r only, and at the ends there is nothing to split: the new leaf is joined to the whole rope. In the middle, the new leaf goes between the two halves. delete is a split at the leaf and a split of one leaf off the rest; at the ends, one split and one half of it.
Why the depth grows as we type: every insertion adds a Cat above the path it walked, and nothing ever removes one. A balanced rope of 325 leaves has depth 9; after a hundred keystrokes at the same place it has a chain of a hundred nodes on one side. The stretch the depth is about earning the bound back.
A2 — record, undo, redo
let record (x : 'a) (h : 'a history) : 'a history =
{ past = h.present :: h.past; present = x; future = [] }
let undo (h : 'a history) : 'a history =
match h.past with
| [] -> h
| x :: rest -> { past = rest; present = x; future = h.present :: h.future }
let redo (h : 'a history) : 'a history =
match h.future with
| [] -> h
| x :: rest -> { past = h.present :: h.past; present = x; future = rest }
A history is two stacks and a present. undo pops the past onto the future, redo the other way; record pushes the present into the past and empties the future, since a new version after an undo forgets the versions undone, as every editor does. Nothing here knows that the versions are ropes: the type is 'a history, and the checks use it on integers too.
What makes this cheap is Part 0's sharing: a version is a root, and two versions a keystroke apart share every node but the path. The panel Versions counts them on notes.txt: 649 nodes and 651, of which 649 are shared. One keystroke adds the new leaf and copies the nodes above it, the depth of the rope plus one.
A3 — fold_until and find_first
let rec fold_until (f : 'b -> 'a -> 'b go) (acc : 'b) (r : 'a rope) : 'b go =
match r with
| Leaf x -> f acc x
| Cat (l, r) -> (
match fold_until f acc l with
| Stop a -> Stop a
| Continue a -> fold_until f a r)
let find_first (p : 'a -> bool) (r : 'a rope) : 'a option =
match fold_until (fun _ x -> if p x then Stop (Some x) else Continue None) None r with
| Stop found -> found
| Continue _ -> None
Block 1's problem was that the function a strict fold receives cannot stop the traversal: the fold calls it on every leaf, whatever it answers. The answer here is a different interface: the function answers Continue or Stop, and the fold looks at the answer before going on. The whole change is in the Cat case: the right subtree is visited only if the left one said Continue. A Stop travels up unchanged.
find_first hands over a function that stops at the first leaf that fits, carrying it in the answer; the accumulator is not needed, so it is None throughout. The key End does this on the part of the rope after the caret: the status line shows the leaves visited, the length of the line, beside the leaves that iter would have visited, all the rest of the document.
A4 — to_seq, with a stack
let to_seq (r : 'a rope) : 'a seq =
let rec go (stack : 'a rope list) : 'a seq =
fun () ->
match stack with
| [] -> Nil
| Leaf x :: rest -> Cons (x, go rest)
| Cat (l, r) :: rest -> go (l :: r :: rest) ()
in
go [ r ]
The state of the traversal is a stack of subtrees still to visit, as session 4's explicit stack for count_notes; the difference is who drives. There, a loop popped the stack until it was empty. Here, a call pops it until a leaf appears, hands the leaf back with the function that will pop the rest, and returns. Nothing is visited until someone calls that function. An empty stack is the end; a Cat on top is replaced by its two children, left first, and we go on at once, since a Cat is not an element.
This is why leaves flattened becomes leaves pulled on the status line, and why the number falls on long.txt: the screen asks for the characters of twenty-four lines and stops asking, and the sequence never touches the rest.
A5 — same and first_difference
let rec same (c1 : 'a seq) (c2 : 'a seq) : bool =
match (c1 (), c2 ()) with
| Nil, Nil -> true
| Cons (x, k1), Cons (y, k2) -> x = y && same k1 k2
| _ -> false
let first_difference (c1 : 'a seq) (c2 : 'a seq) : int option =
let rec go i c1 c2 =
match (c1 (), c2 ()) with
| Nil, Nil -> None
| Cons (x, k1), Cons (y, k2) -> if x = y then go (i + 1) k1 k2 else Some i
| _ -> Some i
in
go 0 c1 c2
Two sequences read in step: one element of each, compared, and the two rests. This is the traversal that a fold cannot do, since a fold walks one collection; with sequences, the consumer holds the two rests and decides when to ask each. The shapes of the ropes never appear, so two ropes of different shape and the same text are same: that is why the mark modified goes away when we type a character and erase it. && stops at the first difference, so same asks for no element after it, and neither does first_difference.
03 — part B
A computation not yet run
B1 — take, map, filter, take_while
let rec take (n : int) (c : 'a seq) : 'a list =
if n <= 0 then []
else
match c () with
| Nil -> []
| Cons (x, rest) -> x :: take (n - 1) rest
let rec map (f : 'a -> 'b) (c : 'a seq) : 'b seq =
fun () ->
match c () with
| Nil -> Nil
| Cons (x, rest) -> Cons (f x, map f rest)
let rec filter (p : 'a -> bool) (c : 'a seq) : 'a seq =
fun () ->
match c () with
| Nil -> Nil
| Cons (x, rest) -> if p x then Cons (x, filter p rest) else filter p rest ()
let rec take_while (p : 'a -> bool) (c : 'a seq) : 'a seq =
fun () ->
match c () with
| Nil -> Nil
| Cons (x, rest) -> if p x then Cons (x, take_while p rest) else Nil
The rule of the block, in every function that returns a sequence: the body begins with fun () ->, so that making the sequence computes nothing, and the source c is asked only inside. take returns a list and so it asks; it tests n before asking, which is what asks for no element more than it returns means, and what makes take 0 of an endless sequence return at once.
filter is the one with a trap. When the element does not fit, we cannot return a sequence that is not yet ready: we are inside the fun (), someone has asked for the next element, and we must find it. So the rest is filtered and called, filter p rest (), at once. On nats with a predicate that is never true, that call never returns: this is the question of the panel Stream, and the answer is that laziness postpones a computation, it does not make an infinite one finite.
B2 — lines
let rec read_line (acc : char list) (node : char node) : char list * char seq =
match node with
| Nil -> (acc, fun () -> Nil)
| Cons ('\n', rest) -> (acc, rest)
| Cons (x, rest) -> read_line (x :: acc) (rest ())
let rec lines (c : char seq) : string seq =
fun () ->
match c () with
| Nil -> Nil
| first ->
let acc, rest = read_line [] first in
Cons (string_of_rev acc, lines rest)
read_line is a loop over the characters up to the next newline: it accumulates them last first (a list grows at its head) and returns the rest of the sequence, the one after the newline. It receives a node, not a sequence, because lines has already asked for the first character to know whether there is a line at all: a document without characters has no line, and a last line without a newline is a line, which is the Nil case of read_line. The empty line is the case where the first node is the newline itself: acc is empty and that is a line.
One line is read per call of the sequence, and the characters of the lines after it are not asked for: lines pulled 24 on long.txt, and the number grows as we scroll.
B3 — grep
let grep (p : string -> bool) (c : string seq) : (int * string) seq =
let rec go (n : int) (c : string seq) : (int * string) seq =
fun () ->
match c () with
| Nil -> Nil
| Cons (s, rest) -> if p s then Cons ((n, s), go (n + 1) rest) else go (n + 1) rest ()
in
go 1 c
filter again, with a counter that goes up whether the line fits or not, so that the number is the line's number in the document and not among the matches. The panel Find a line asks for one element of this sequence: the lines up to the match are asked for, and not one after.
04 — part C
The rest of the computation
Part C goes with session 6, on continuations: these solutions are to be read after that lecture.
C1 — iter_k
let rec iter_k (f : 'a -> (unit -> 'r) -> 'r) (r : 'a rope) (k : unit -> 'r) : 'r =
match r with
| Leaf x -> f x k
| Cat (l, r) -> iter_k f l (fun () -> iter_k f r k)
Compare with iter: there, the Cat case visits l, and when that returns, visits r; the machine keeps visit r, then return to whoever called us in a frame. Here we write that frame ourselves: fun () -> iter_k f r k is the rest of the traversal after the left subtree, and it is passed down as k. At a leaf, f receives the leaf and k, and it is f that decides whether the traversal goes on. Every call is in tail position, so the machine's stack does not grow; the nesting of the closures grows instead, one per Cat on the path.
The panel Trace hands over an f that returns k without calling it. The traversal stops after one leaf, and what the editor holds is a function: the rest of the traversal, as a value. Calling it visits the next leaf and returns the next rest. This is what session 6 says a continuation is, and it is what a generator's object does in block 1.
C2 — to_seq, in one line
let to_seq (r : 'a rope) : 'a seq =
fun () -> iter_k (fun x k -> Cons (x, k)) r (fun () -> Nil)
The f handed over puts the leaf and the rest of the traversal into a Cons, and the rest of the traversal has exactly the type of a sequence, unit -> 'a node. Nobody writes the stack of A4: it is inside k, as the closures that iter_k built on the way down. The screen is drawn from this sequence as it was from the other; same and first_difference take it without a change, since they know a sequence by its type only.
C3 — find, three ways
let find_raise (type a) (p : a -> bool) (r : a rope) : a option =
let exception Found of a in
try
iter (fun x -> if p x then raise (Found x)) r;
None
with Found x -> Some x
let rec find_k (p : 'a -> bool) (r : 'a rope) (k : 'a -> 'r) (h : unit -> 'r) : 'r =
match r with
| Leaf x -> if p x then k x else h ()
| Cat (l, r) -> find_k p l k (fun () -> find_k p r k h)
let find_cps (p : 'a -> bool) (r : 'a rope) : 'a option =
find_k p r (fun x -> Some x) (fun () -> None)
Three ways to leave a traversal before its end. With iter the function cannot stop it, so it leaves by an exception: raise throws the frames away up to the try. With fold_until (A3) the function answers Stop and the fold stops itself. With two continuations, the function has two exits in its hands: k, what to do with the leaf found, and h, what to do when this subtree has none. In the Cat case, h for the left subtree is look in the right one; at a leaf that fits we call k and never come back to h, so the rest of the rope is not visited.
raise is h: an exception calls the handler that was installed where the try is, and try … with is where h was given. The panel shows the same leaves visited for the three ways: the difference between them is not what is visited but who holds the exit.
C4 — match_k
let rec match_k (p : pattern) (c : char seq)
(succ : char seq -> (unit -> 'r) -> 'r) (fail : unit -> 'r) : 'r =
match p with
| [] -> succ c fail
| Lit x :: rest -> (
match c () with
| Cons (y, c') when x = y -> match_k rest c' succ fail
| _ -> fail ())
| Any :: rest -> (
match c () with
| Cons (y, c') when y <> '\n' -> match_k rest c' succ fail
| _ -> fail ())
| Star :: rest -> (
match c () with
| Cons (y, c') when y <> '\n' ->
match_k p c' succ (going_back (fun () -> match_k rest c succ fail))
| _ -> match_k rest c succ fail)
let matches (p : pattern) (c : char seq) : bool =
match_k p c (fun _ _ -> true) (fun () -> false)
A pattern is matched item by item; when the pattern is empty the match is complete, and we hand the rest of the sequence to succ. A literal or a ? asks for one character and goes on or fails. The star is the one with a choice: take one more character, or end here. It takes the character first, greedily, and puts the other choice into the failure continuation: if what follows does not work out, come back and try the pattern after the star from here. Going back is possible because the sequence is persistent: c, the position before the character, is still there when fail is called, and reading it again gives the same character.
succ receives fail along with the rest, so that whoever comes after the match can also say no: search, given, uses it to try the next position, and the stretch all the matches uses it to ask for the next end. On f*n in we can stop at the first one., the star takes the whole line and gives back one character at a time, three times, until an n follows: the status line reads went back 3, counted by going_back.
05 — the warm-up
The sheet, worked
The questions on paper and the exercises at the keyboard, with their answers: the sheet, worked (PDF). The files: warmup.ml, 25 checks, and the homework queue.ml, 4 checks, both run with ocaml on the file.
Two things worth reading there even when our own answers pass. Exercise 1's last question: from add_pair : int * int -> int there is no add3 without writing a new function, whereas add 3 is already one; that is what currying buys. And exercise 10: two readers of pascal build every row twice, twelve for six rows, and one lazy per row brings it back to six, which is the lecture's third choice, how many times.
06 — the stretches
Where the homework goes
- The depth.
rebalance r = of_list (to_list r)is a correct answer, in one line, and it is whatof_stringalready does: the balanced rope. The question is when to call it. A rule that works: after an edit, if the depth is more than twice the depth of a balanced rope of the same length,2 * log2 (length r). Rebalancing costs a full traversal, so it must be rare; the rule makes it happen once in a long run of keystrokes. - Pieces of text in the leaves. With
string rope,fold,depth,to_seq,iter_kand everything in Parts B and C do not change: they never look inside a leaf.length,split,insertanddeletedo: a position now falls inside a leaf, and a split cuts the string. That is the whole of the change, and it says which functions were about the tree and which were about the characters. - All the matches.
match_k p c (fun after fail -> Some after :: ...)is the wrong shape; the way is asuccthat records the end and then callsfail, so that the star gives back one more character and the next end is found. The results come longest first, and the recursion ends when the innermostfail, the one given at the start, returns the list. - A tune without end.
let rec cycle xs = fun () -> ...: a sequence that reads the list and, at its end, starts the list again;take 16of it goes towav.ml. The trap iscycle [], which is a loop; the melody of lab 3 is never empty.