PP26  ·  Lab 2  ·  part C · reading guide · OCaml

Three Holes in a Queue

ocaml/lib/pqueue.ml is 42 lines, and three of its functions are missing. The fourth hole from Python — _rev — is not here: List.rev already exists, and OCaml's own list is the cons-list. This note walks through what each hole is for, what the interface in pqueue.mli promises on its behalf, and how to recognise a correct result — without supplying the three definitions.

01 — the file

What is given, and what is left to write

Three bodies are missing, ordered so that each may use the one before it. The list reversal Python made you write is a library call here.

linenamestatuswhat it is
12type 'a tgivenA record of two lists, { front; back }. Abstract in the .mli, so nobody outside this file can see the fields.
14emptygivenBoth lists empty. One value, shared by every queue that ever runs dry.
16is_emptygivenChecks front only — legal precisely because of the invariant.
21makeTODO 1The smart constructor that restores the invariant. Internal: not in the .mli.
26enqueueTODO 2Add at the back. O(1). Note the argument order: element first, queue second.
31dequeueTODO 3Take from the front, returning the value and the new queue — as an option.
36peekgivenA match on q.front. One pointer. Never searches.
38to_listgivenThe abstraction function, q.front @ List.rev q.back. The tests measure the implementation against it.
42of_listgivenEnqueue every element of a list, via List.fold_left — a higher-order function met properly in session 5.

Read pqueue.mli first. It is the lecture's point made syntax. type 'a t is abstract there, so outside this file a queue can only be built through empty, enqueue and of_list — the invariant needs keeping in one file only. And dequeue : 'a t -> ('a * 'a t) option says the whole story in one line: the value and the new version, or None.

02 — the representation

Two lists, and the language's own cons

The same trick as in Python: two lists pointing in opposite directions, so that both ends of the queue are somebody's head. What changes is that the cons-list is built in — [] is empty, x :: rest is a node — and immutable by decree rather than by discipline.

ocaml/lib/pqueue.mllines 3–6, 12
type 'a t = { front : 'a list; back : 'a list }

contents q  =  q.front @ List.rev q.back

invariant:     q.front = []  ⟹  q.back = []
The invariant is what makes peek a two-case match. Forbid the state where the front is empty while elements sit in the back, and every reader gets simpler. make is the one place the invariant is restored; everything else just calls it.

What Python could only ask for — do not touch the nodes — is now not a request. An OCaml list has no operation that writes into a cell. The only mistake still available is the structural one: rebuilding a list that should have been shared. Nothing in the test suite catches that; the solver's --inspect and the benchmark in part D are where it would show.

03 — todo 1

make front back — the smart constructor

The heart of the data structure, and a two-case match. Every other function builds queues by calling it, never by writing a record literal — that is the whole reason the invariant holds everywhere.

ocaml/lib/pqueue.mllines 18–23
(* TODO 1: smart constructor. Restore the invariant: if [front] is
   empty, the reversed [back] must become the new front. Build every
   queue below through [make] and the invariant holds everywhere. *)
let make front back =
  ignore front; ignore back;
  failwith "TODO 1: make"
The two ignore lines exist only to keep the stub compiling without unused-variable warnings. Delete them together with the failwith.

Match on front alone:

  • Front is non-empty. Nothing to fix. Return { front; back } as they stand — and they are the same lists that were passed in, because OCaml never copies a list unless asked to.
  • Front is empty. The invariant demands the back be empty too, so move it: List.rev back becomes the new front and the new back is []. If back was also empty this quietly produces empty — no special case needed.

The tempting wrong version. Reversing unconditionally — always putting List.rev back @ front in the front — passes every test in the runner and destroys the performance story: every enqueue becomes O(n). No test here inspects the representation, so this one is on you. Branch on the front.

04 — todo 2

enqueue x q — add at the back

One cons and one call. A version longer than a line is probably doing work that belongs to make.

ocaml/lib/pqueue.mllines 25–28
(* TODO 2: cons [x] onto [back]; keep [front] as it is (shared!). *)
let enqueue x q =
  ignore x; ignore q;
  failwith "TODO 2: enqueue"

Put x at the head of q.back and hand both halves to make. Do not build the record yourself: enqueueing onto empty would leave an empty front with a one-element back, which is precisely the state the invariant forbids. make is what catches that.

shares

The new queue points into the old one. Both versions stay usable.

let q1 = Pqueue.of_list [1; 2; 3]
let q2 = Pqueue.enqueue 4 q1

(* q2's front IS q1's front —
   the same list, not a copy *)
q2.front == q1.front   → true

One new cons cell and one new record exist after the call. Three elements were reused untouched.

the argument order

Element first, queue second — the .mli fixes it.

val enqueue : 'a -> 'a t -> 'a t

(* so this reads naturally: *)
q |> Pqueue.enqueue 4 |> Pqueue.enqueue 5

The same convention as List.cons. Get it backwards and the compiler tells you before any test runs.

The O(1) claim survives the make call: it only reverses when the front is empty, and then the invariant says the back was empty too, so the list being reversed holds exactly the one element just consed. Constant work, always.

05 — todo 3

dequeue q — take from the front

The one operation that returns two things, because a persistent structure cannot surrender the value by mutating itself. The type says so: ('a * 'a t) option.

ocaml/lib/pqueue.mllines 30–33
(* TODO 3: take the head of [front]; rebuild the rest through [make]. *)
let dequeue q =
  ignore q;
  failwith "TODO 3: dequeue"

Two cases, and the empty one costs no exception. Where Python raised IndexError, the type here has a None arm — peek above shows the exact shape. Otherwise the head of the front is the value, and the queue returned is built from the front's tail and the untouched back, passed through make. That call is where the front can run dry and trigger the flip.

Forget the empty case and the compiler says so: a non-exhaustive match is a warning that dune's default profile promotes to an error. It is the first of several things the checker now does that Python left to a test.

Why the old queue still works afterwards

Nothing in those two cases writes anywhere. The cell holding the old head is still there, still pointing at the same tail; the new front simply is that tail. That is why the fan-out test can dequeue the same version twice and get the same answer both times, then push the two results in different directions. One present, several futures.

06 — the tests

What each group asks

The runner in test/test_pqueue.ml is hand-rolled: every check runs whatever the others do, and the tally at the end measures progress. A check that reaches a stub's failwith is reported as todo; any other failure is WRONG.

groupasksif it fails
basicsdoes it work at all?Empty cases and the single-element round trip. Usually a Some/None mix-up, or a pair built the wrong way round.
FIFO contractis it a queue?Order under interleaving, plus 1000 pseudo-random operations checked against a plain-list model. A mismatch means the abstraction function and the implementation disagree.
persistenceis it persistent?Old versions survive an enqueue and a dequeue; the same version dequeued twice yields the same value, and the two futures diverge. These are the tests the lecture is about.

Finishing TODO 1 alone changes nothing on screen. make is internal — not in the .mli, not called by any test. The first visible movement comes with TODO 2, and the round trip needs TODO 3. Work top to bottom and expect the tally to sit still for a while.

07 — run it

The working loop

$ cd ocaml
$ dune runtest # after every TODO
# once everything is green — the queue drives a real search:
$ dune exec bin/solver.exe -- ../mazes/medium.txt --bfs
$ dune exec bin/solver.exe -- ../mazes/medium.txt --bfs --html=bfs.html # time travel
$ dune exec bin/solver.exe -- ../mazes/medium.txt --bfs --inspect=40 # ask an old version

On mazes/medium.txt the BFS run should report 306 cells explored, path length 75 — the same numbers as the Python and Java solvers. Same specification, same search, same answer.

When progress stalls

  • Everything reports todo. Expected — that is the starting state, and TODO 1 alone moves nothing because make is internal.
  • Error: this pattern-matching is not exhaustive. dequeue is missing its [] case.
  • A type error mentioning a tuple where 'a t was expected. A queue was written as (front, back); it is a record, { front; back } — and should come from make anyway.
  • Values are right but shifted by one. dequeue rebuilt from q.front instead of from its tail.
  • “1000 random ops” goes WRONG at once. enqueue consed onto the front instead of the back, or make reversed the wrong list.
  • Warnings about unused values. The ignore lines are still there. Delete them with the stub.

Next: ocaml-architecture.html — what the types are for: how the solver is composed around this module, and what the compiler checks on the way.