A Postscript to Curious OCaml: OxCaml, Rust and Lean

The book keeps four promises at run time or by a test. What each language would do with them, and what changes when agents write the code

Chapter 8 of Curious OCaml builds a small module for reading files. A function opens a file, hands its caller a reader, and closes the file when the caller has finished, however it finishes.

(* The callback owns the resource scope; an escaped reader is
   invalidated. *)
let with_source ~acquire ~read ~close consume =
  let resource = acquire () in
  let active = ref true in
  let next () =
    if not !active then
      invalid_arg "reader used outside its scope";
    read resource in
  Fun.protect
    ~finally:(fun () -> active := false; close resource)
    (fun () -> consume next)

The comment makes a promise: nobody will read through next after the file is closed. The types do not keep it. A caller can return next, or store it somewhere, and OCaml will compile the program. So the module keeps the promise itself, with the flag active, and the chapter says so: “The type system does not prevent the escape; the check happens at run time.”

A promise like this can be checked at five different times. It can be left in the comment, where nothing checks it. It can be checked while the program runs, as the flag does. It can be checked by a test, on the inputs the test tries. It can be checked by the compiler, in every program that uses the module. It can be proved, for every input. The five run from latest to earliest. Languages differ in how far along that order a promise can be moved, and in what the move costs.

The fourth edition of the book is finished, and this essay is a postscript to it. The book is written in OCaml and does not mention OxCaml, Rust or Lean. We count four promises in it that OCaml leaves to run time or to a test, and each is one that some other language checks sooner.

Part I takes three promises about ownership: a reader that must not leave its scope, a continuation that must be used once, and data that two threads must not change at the same time. It ends on a question I wanted answered plainly: is OxCaml simply better than Rust? Part II takes the fourth promise, the laws that the book tests and does not prove. It ends on a second question: is Lean simply better than the other three for an AI, because an agent that proves as it goes gets feedback that no test can give?

I should say where I stand. I have written OCaml for more than twenty years. Rust I bounced off, as I told in Programmer: A Memoir. Lean I have followed without writing, and OxCaml I have not written either. For some months agents have written all of my code. The programs in this essay were written and run by agents on my machine, directed by Claude, and my part was to ask and to read. Where the essay says “we”, it means the two of us.

An earlier essay here, Dependent Types from Rocq to Lean 4, which I wrote with GPT-6 Astra and Claude Opus 5.5, ends with the sentence “Reading Lean means seeing those promises in the type.” This one is about the promises that are not in the type.

The book

Curious OCaml began as a course on functional programming that I taught in 2012 and 2013 to a handful of students. The lectures became a book in January 2026. The fourth edition has thirteen chapters and about eight hundred pages.

It teaches programming through types, logic and algebra, and its method is to follow one construction at a time until its meaning is plain. A pair is a proof of a conjunction. A tree with a hole in it is a position in an editor. An evaluator becomes a machine when its continuations are turned into data. The first part asks what a program means and which laws it satisfies. The second carries one small language of expressions through several representations. The third is about computation spread over time and over choices, and the question the introduction gives it is one this essay keeps returning to: “Who chooses, when does work happen, and who owns suspended work?” The last chapter looks back at all of it through category theory.

This edition adds sections on exceptions and mutable state, on generalized algebraic data types, on a unifier and type inference for a small language, on deletion from a red-black tree, on automatic differentiation written as a fold, on a model where particle filtering pays for itself, and on the semi-naive evaluation of Datalog. It also has more than a hundred diagrams, drawn from the values that the programs compute.

The programs in the text run. The chapters hold 1045 blocks of OCaml. All but 21 are executed, or compared with a compiled source file, each time the book is built, and the build takes about five seconds. The larger programs live in their own modules with tests of their laws. The introduction is exact about what that establishes: “A passing test is evidence about its inputs, not a proof for all inputs; the proof exercises are there for the difference.”

Here are the four promises.

  1. Chapter 8: a reader is not used outside the scope that opened its file. Kept by a flag.
  2. Chapter 10: a suspended computation is resumed exactly once. Half kept, by an exception.
  3. Chapters 3 and 10: no code changes a mutable cell that other code is relying on. Kept, in the book’s scheduler, by running everything on one thread.
  4. Chapter 4 and after: a module satisfies its laws. Kept by tests.

Part I. Ownership

The reader that must not escape

OxCaml is Jane Street’s version of the OCaml compiler. It was announced under that name in June 2025. It is the compiler the firm itself uses, and it is designed to accept every OCaml program unchanged. What it adds has to be asked for.

Its largest addition is modes. A type says what a value is. A mode says how one particular value may be used: whether it may outlive the place where it was handed over, whether another reference to it exists, whether another thread may be looking at it.

The mode for the reader is local. A region is roughly the extent of a call, and a local value may not outlive the region it was given to. A function that takes an argument at mode local promises not to keep it. The book’s module needs one change, in its first line. The function it is given, consume, is declared to take the reader locally.

let with_source ~acquire ~read ~close
    (consume : (unit -> 'b option) @ local -> 'a) =

The bodies stay as they were. A caller that returns the reader is now rejected by the compiler:

File "ox_escape1_return.ml", line 2, characters 64-68:
2 | let escaped = Oxcaml_scoped.with_lines "three.txt" (fun next -> next)
                                                                    ^^^^
Error: This value is local to the parent region but is expected to be global.

So is a caller that stores the reader in a reference, and one that returns a function which calls it. The agent that ran this tried twelve ways round, among them an exception carrying the reader, a mutable field, a lazy value and another thread. The compiler refused eleven. The twelfth was a hand-written external that declares the identity function to turn local values into global ones:

external leak : 'a @ local -> 'a = "%identity"

It compiled without a warning. Twelve attempts are not a proof, but as far as we could tell the flag in the book’s module had become dead code for any program that does not set out to defeat it.

In its shortest form the annotation is nineteen characters. Its cost lies elsewhere, and the book’s own next page shows it. Chapter 8 goes on to use the reader:

let first_lines n filename =
  Scoped.with_lines filename (fun next ->
    stake n (stream_of_reader next))

stream_of_reader turns a reader into a lazy stream, whose tail is a function that holds the reader, and stake takes the first n elements. Against the annotated module this is rejected. The compiler has a point, since a stream that holds the reader could carry it out. It cannot see that stake uses the stream up on the spot. To get the three lines accepted, the agent wrote a second kind of stream whose tails are themselves local:

type 'a lstream =
  | LNil
  | LCons of 'a @@ global * (unit -> 'a lstream @ local)

let rec lstake n s =
  match s with
  | LCons (a, t) when n > 0 -> a :: lstake (n - 1) (t ())
  | _ -> []

let rec lstream_of_reader next = exclave_
  match next () with
  | None -> LNil
  | Some x -> LCons (x, fun () -> exclave_ lstream_of_reader next)

let first_lines n filename =
  with_lines filename (fun next ->
    lstake n (lstream_of_reader next) [@nontail])

@@ global says that a field never holds a local value. exclave_ builds a result in the caller’s region and not in the function’s own. [@nontail] stops a call from being a tail call, so that the region is still there when the call returns. That is a new type and five annotations for three lines of client. Nothing says that lstake and lstream_of_reader take their arguments locally. The compiler infers it.

Parts of the standard library have the same problem. List.init, List.iter and Seq.unfold refused the local reader, because their signatures do not promise to let go of what they are given. Jane Street’s documentation shows its own libraries annotated for this. A library written for plain OCaml is not.

A helper function written in the same file accepted the reader, since OxCaml infers modes within a file. The same helper in a file of its own did not, with an ordinary interface or with none. A parameter is inferred local only when a use in the same file needs it, and otherwise it is exported as global. So whether a library works with local values depends on what it declares and not on its code. The compiler we installed has an experimental extension that infers the general mode and exports it. With it the helper worked from its own file.

There is also something local cannot say. It has two levels: local to this region, or global. It cannot say “as long as that particular outer scope”. The designers give the example themselves: Rust’s lifetimes “can express patterns that our locality modes cannot: for instance, an arena allocator can allocate new values whose lifetime is a particular enclosing region”.

Rust checks the reader’s promise with a lifetime, which is a name for a scope that appears in types. Here is a direct translation of the book’s module, specialized to the lines of a file:

fn with_lines<R>(
    path: &str,
    consume: impl FnOnce(&mut dyn FnMut() -> Option<String>) -> R,
) -> R {
    let mut lines = BufReader::new(File::open(path).unwrap()).lines();
    let mut next = || lines.next().map(|r| r.unwrap());
    consume(&mut next)
}

No lifetime is written. The &mut lends the reader to consume for a lifetime that the compiler fills in, and the result type R cannot carry that lifetime out. A consumer that returns the reader is rejected with “lifetime may not live long enough”. But a Rust programmer would not write the module. They would write the client:

fn first_lines(n: usize, path: &str) -> std::io::Result<Vec<String>> {
    BufReader::new(File::open(path)?).lines().take(n).collect()
}

The file is a value. When the value goes out of scope its destructor closes the file, on every path out of the function. A reference into the file that tries to outlive it is refused: “cannot return value referencing local variable file”. Everything Chapter 8 builds by hand, the scope function, Fun.protect, the flag, is what Rust does with any value.

Releasing a resource when the value that holds it goes out of scope is the idiom I valued most in C++, where it is called RAII. I wrote in the memoir that I have no equivalent of it in OCaml. Rust is that idiom checked by the compiler. It is not airtight: a program may call std::mem::forget on the file and skip the close, and the documentation is frank that “Rust’s safety guarantees do not include a guarantee that destructors will always run.”

Lean 4 gives a third answer. Its library has a function shaped like the book’s, IO.FS.withFile, and it closes nothing. A handle returned from it still reads:

def main : IO Unit := do
  let h ← IO.FS.withFile "three.txt" .read (fun h => pure h)
  IO.println (← h.getLine)

The program prints the first line of the file. Lean counts the references to every value, and the handle is closed when the last one goes. The agent watched the file descriptor disappear from the process after the handle’s last use. There is no annotation and no static check, and the escape does no harm, because the file is never closed while someone can still reach it.

Rust, then, has the idiom I valued most in C++, and I bounced off it all the same. In the memoir I guessed that its syntax felt bloated, and I was not sure. The two Rust functions above give the guess something to stand on. The return type of the second is std::io::Result<Vec<String>>. Written as OCaml writes types, with the argument first and no brackets, it would be string vec Std.Io.result. The Rust spelling takes eleven presses of the shift key and the OCaml spelling two. We also counted punctuation in the programs written for the reader and the continuation. With comments and the contents of strings removed, it is 30 percent of the characters in the Rust files, 18 percent in the OCaml and 20 percent in the OxCaml. The files are few and short.

Spelling is not all of the weight. A Rust function must write out its signature, where OCaml infers one, and the signature marks each borrow. OxCaml’s local stream carries five marks of the same kind. It spells them as words, local, global and exclave_, and its punctuation hardly rises. The local stream reads fine to me. So part of what I felt as bloat was spelling.

The other part Rust has from C++. Both languages make the programmer write distinctions that matter to how a program runs and not to what it computes. The signature of with_lines shows it. In OCaml the function’s type is string -> ((unit -> string option) -> 'a) -> 'a: a path, a consumer of the reader, and the consumer’s result. The Rust signature says the same and more. impl and dyn say how the two calls are compiled. &str and String say who frees a piece of text. FnOnce, FnMut and &mut say whether a function is consumed by its call, changed by it, or lent. None of this changes which lines come out.

RAII ties how a program runs to what it does. A loan is seldom essential to what a function computes. In this signature the &mut is what keeps the reader inside its scope. The same goes for ownership. Who owns a piece of text matters only to how the program runs. Who owns a file decides when the file is closed, and that is part of what the program does. Rust has one mechanism for both, so every string is written with the care that only the file needs. Lean also has one mechanism for both, the reference count, and writes nothing for either.

Much of the difference is in the defaults. In Rust every value is owned or lent, and each signature says which. In OxCaml a value is shared and collected unless a mode says otherwise, and within a file the compiler infers the modes of functions. What had to be written for the local stream were two marks in a type and three about regions. exclave_ and [@nontail] are about how the program runs, as dyn and String are. OxCaml asks for them only where a mode has been asked for.

The continuation that must be used once

Chapter 10 is about effect handlers. A handler receives the rest of a computation as a value, the continuation k, and decides whether and when to resume it. The chapter states the rule:

OCaml continuations are one-shot. A continuation is the suspended stack itself, not a copy of it, and resuming it uses it up.

A second resumption raises an exception, and the chapter shows one:

type _ Effect.t += Pause : unit Effect.t

let () =
  match Effect.perform Pause with
  | () -> ()
  | effect Pause, k ->
      Effect.Deep.continue k ();
      (match Effect.Deep.continue k () with
       | () -> assert false
       | exception Effect.Continuation_already_resumed -> ())

And then the other half:

Resuming twice is detected. Resuming never is not, and is worse. A suspended computation may be in the middle of a Fun.protect, holding a file or a lock whose release code runs only when the computation returns or raises. If the handler simply forgets k, that code never runs.

“Exactly once” is two rules: at most once, and at least once. A type system that enforces the first is called affine, and one that enforces both is called linear. OCaml checks the first rule at run time and the second not at all.

We expected OxCaml to have moved the first rule into the compiler. It has the modes for it: a value at mode once may be used a single time. But the interface to effects that ships with OxCaml does not use them. Its continue takes a continuation at no particular mode and raises the same exception as before.

The mode can say it, though. The agent wrote a wrapper of about twenty lines in which a handler receives its continuation at mode once:

type ('a, 'b) k
val continue : ('a, 'b) k @ once -> 'a -> 'b
val discontinue : ('a, 'b) k @ once -> exn -> 'b

With it, a handler that resumes twice does not compile:

File "oneshot_double.ml", line 9, characters 29-30:
9 |             Oneshot.continue k ())
                                 ^
Error: This value is used here,
       but it is defined as once and has already been used at:
File "oneshot_double.ml", line 8, characters 29-30:
8 |             Oneshot.continue k ();
                                 ^

The second rule stays unchecked. A handler that drops k is accepted with the wrapper or without it, and the finally of the suspended computation never runs. No compiler in this essay checks it.

What OxCaml did add to effects answers a different sentence of the chapter. The chapter’s first effect asks its surroundings for a string:

type _ Effect.t += Ask : string Effect.t

let greeting () = "Hello, " ^ Effect.perform Ask

The type of greeting is unit -> string, with no mention of Ask, and the chapter draws the consequence: “OCaml does not track in types which effects a function may perform, so a missing handler is found only at run time.” In OxCaml the safe way to perform an effect takes a token, which a handler supplies and which is proof that the code is running inside one.

let greeting h () = "Hello, " ^ Effect.Safe.perform h Ask
let polite h () = greeting h () ^ "!"

Every function between the handler and the perform passes h along. Chapter 10 names three things that change when a program moves from monads to effects, and the second is “No infection”: code that performs no effects “is used unchanged, and so is code that merely calls a function that performs them.” The token brings a little of the infection back. It also proves less than one would like. It shows that some handler is installed, and not that the handler knows this effect. A program whose handler handles Ask and whose body performs something else compiles, and stops at run time with Effect.Unhandled.

The experiment turned up one thing nobody had asked about. The first two promises meet. Take a consumer of the scoped reader that performs an effect while inside the scope, and a handler that drops the continuation.

(match
   Scoped.with_source
     ~acquire:(fun () -> open_in "three.txt")
     ~read:(fun ch -> try Some (input_line ch) with End_of_file -> None)
     ~close:(fun ch -> incr closes; close_in_noerr ch)
     (fun next -> ignore (next ()); Effect.perform Pause; ignore (next ()))
 with
 | () -> ()
 | effect Pause, _k -> ());   (* continuation forgotten *)

The scope is never left, so the file is never closed. The run printed closes = 0. This holds in OCaml and in OxCaml alike. The flag does not see it and the mode does not either.

Rust has no effect handlers. Its nearest thing is a closure of type FnOnce, which may be called once.

fn handler(k: impl FnOnce(i32) -> i32) -> i32 {
    k(1) + k(2)
}

The compiler rejects the second call with “use of moved value: k”, and adds a note: “FnOnce closures can only be called once”. Rust also does something for the second rule. A closure that is dropped without being called runs the destructors of what it had captured, so a file it had captured is closed after all. mem::forget gets round that too. And Rust pays in another place. A function that may suspend has a different type from one that may not, and its callers must be marked in their turn, which is the infection again.

Two names for one cell, and a second domain

Chapter 3 has a new section on mutable state. Shortened to four lines, its example is:

let a = ref 1 in
let b = a in        (* the same location as a *)
b := 2;
assert (!a = 2)

Its plainest paragraph says what the lines show:

Aliasing is the reason why state makes programs harder to reason about. What we know about an immutable value stays true for as long as its name is in scope. What we know about !a can be changed by an assignment anywhere in the program, through any alias, in a line that does not mention a.

Chapter 10’s scheduler avoids the worst case by construction. Its tasks take turns on one domain, which is OCaml’s word for a thread that can run in parallel with others, and the chapter notes that running them on several “would need synchronization that this runtime does not have.”

OCaml 5 lets a program race. Two domains may read and write one cell with nothing between them. The language limits the damage: the manual promises that “even for programs with data races, memory safety is preserved”, and that a race cannot disturb unrelated data or earlier and later moments of the program. A detector finds the races that happen in a given run.

OxCaml moves this promise into the compiler with two more kinds of mode. A function is portable if it may be sent to another domain. A value is contended if another domain may be writing to it, and then its mutable fields may not be touched. The documentation’s example:

let cheer_up (t @ contended) =
  t.mood <- Happy
Error: This value is contended but expected to be uncontended.

Mutable state that domains share is wrapped in a capsule, a value whose contents can be reached only while its lock is held. The design has a soundness proof, and it is in use in Jane Street’s codebase of eighty million lines.

It has a price in concepts. OxCaml’s documentation now lists nine separate axes of mode, new modes were still being added this April, and the libraries for parallelism are versioned as previews.

Rust gives the same guarantee and one more. A value that is being changed through one reference cannot be read through another, even on a single thread. Here is the chapter’s example in Rust:

let mut cell = 1;
let a = &cell;
let b = &mut cell;
*b = 2;
assert!(*a == 2);
error[E0502]: cannot borrow `cell` as mutable because it is also borrowed as immutable

So Rust restricts the aliasing of Chapter 3 itself. As far as its documentation shows, OxCaml leaves a single domain as the book describes it, and steps in only where a second domain could look.

The rest of OxCaml is about speed. A local value can be allocated on the stack. Numbers can be stored unboxed, without a pointer. A function can be marked so that the build fails if it allocates. We found no figures from Jane Street on what these buy. Two outsiders have measured: one saw the slowest thousandth of his packets fall from 29 nanoseconds to 9, and another saw a numeric loop run 1.44 times faster.

Here is where the first three promises stand, with the missing handler added. The OCaml, OxCaml and Rust columns were established by running programs, and the Lean column partly from its documentation.

Promise OCaml 5.5 OxCaml Rust Lean 4
The reader does not escape at run time, by a flag by the compiler, with one annotation by the compiler, and the scope function is unnecessary not checked, and harmless
The file is closed on every exit by Fun.protect, unless the caller is suspended and dropped the same by a destructor, unless forgotten by a reference count
The continuation is not resumed twice at run time, by an exception at run time, unless a wrapper is written by the compiler, for a closure no continuations
The continuation is not dropped never never cleanup runs when it is dropped, unless forgotten no continuations
The effect has a handler at run time by the compiler, for some handler no effects by the compiler, as a monad

Is OxCaml simply better than Rust?

No. The two start from opposite ends, and the people who built OxCaml say so: “whereas Rust starts from an ownership-based type system (with rigid control over aliasing) and makes it more flexible through the use of lifetimes and borrowing, OxCaml starts from a very flexible language and supports more careful control over aliasing through the use of modal types.”

Each can say things the other cannot. Rust can name a scope and tie a value to it. It can lend a value for writing and take it back. It can produce a program with no runtime system under it, and so it is used in the Linux kernel. Its traits find the implementation that fits a type without being told, which OCaml’s modules do not. OCaml and OxCaml share data freely, because a collector frees what nobody holds. They have functors, which are modules that take modules as arguments, and they have effect handlers, generalized algebraic data types and guaranteed tail calls. Rust has none of the four.

They differ also in how their features combine. In OCaml most features can be used without thought for the others, and much of that follows from the collector: when nobody has to say who frees a value, a closure is just a function. Rust’s ownership reaches into every feature. It has three kinds of closure and two kinds of string, and a function that may suspend has a type of its own. OxCaml shows both sides, because it adds ownership to a language built without it. A program that asks for no mode is unchanged, and a mode belongs to a value and not to its type. Where a mode was asked for, features stopped being independent: a local value and a tail call, a local reader and a lazy stream. OCaml has such a place of its own, where a suspended computation meets the cleanup it owes.

The collector’s worth has been measured once that we could find. In a controlled trial, students given an optional garbage collector for Rust were more likely to finish a task with tangled aliasing, and those who finished took about four hours where the others took about twelve. Rust’s speed has been measured many times. On the usual small benchmarks, where each language is set against C (OCaml, Rust), Rust runs from a little faster than OCaml to eight times faster. It wins the one that is mostly allocation by using an arena, a block of memory freed all at once, which is the workaround for not having a collector.

OxCaml is less finished than its papers suggest. On the day we installed it, its website gave a command for a compiler one base version behind its own package repository. Two mode keywords of the earlier syntax, unique_ and once_, are gone. Updating a uniquely owned value in place, the headline of the 2024 paper, is not yet a stable part of the compiler. None of the mode system has been proposed for the main OCaml compiler, and Jane Street’s documentation gives the reason: the extensions are “too fresh and too much in flux to be good candidates for inclusion in OCaml”. What has been taken up from OxCaml are smaller things: labeled tuples, immutable arrays, polymorphic parameters. And on how well agents write OxCaml there is no measurement of any kind, only Jane Street’s report that they do.

Much of what decides between them is not on the page of either language. Rust’s package registry holds about 390,000 packages and OCaml’s about 4,750. Rust has promised since 2015 not to break programs. OxCaml’s front page says that it “makes no promises of stability or backwards compatibility for its extensions”. Rust treats Windows as a first-class platform. OCaml got its port to Microsoft’s compiler back last year, in version 5.3. Rust has the larger set of verification tools by far, which matters in Part II.

Meta is the plainest example. Two well-known type checkers written in OCaml there have left for Rust. Pyre, for Python, was rewritten as Pyrefly. Its authors gave their reasons: “OCaml’s ecosystem has historically struggled with Windows”, and parallelism before OCaml 5 was awkward. They add: “Switching to Rust also allowed us to grow our community of contributors much faster than if we had continued with OCaml.” Flow, for JavaScript, now describes itself as “written in Rust”. Most of its OCaml was removed from the repository this June, and no reason has been published. A type checker is the kind of program OCaml is best known for. The reasons given are about platforms, the runtime before OCaml 5, and people. None is about the type system.

My own case is different from Meta’s. My main project, OCANNL, compiles tensor programs to C and to GPU code. In the memoir I gave my excuse for not needing Rust: the fast code in the project is generated, so the language I write in can afford its collector.

A language can help with generating code in three ways. The first is to compile code while the program runs. In 2003 I was doing genetic programming and wanted to run the programs it evolved, and Xavier Leroy pointed me to MetaOCaml, in which a program builds typed code and runs it. OxCaml now has the same idea in the compiler. A post from Jane Street this month describes it: <[ 2 + 3 ]> is a quotation, an expression of type int that has not been evaluated yet, and its own type is <[int]> expr. Quotations are spliced into one another, and the result is compiled and run while the program runs. They use it to compile a small language for numeric kernels.

The second is macros: code that runs while the program is being compiled. Rust has them. OCaml has preprocessors instead, separate programs that rewrite the syntax tree of a file before it is type-checked. Typed macros for OCaml have been a research project since 2015, with Leo White of Jane Street among its authors. Its design of 2023, MacoCaml, marks a definition with macro to have it run at compile time, and builds code with quotations and splices like OxCaml’s. A well-typed macro can generate only well-typed code. MacoCaml is implemented in a fork of the OCaml compiler, and the fork was still being worked on this month. As far as we found, OxCaml has the quotations and not the macros.

The third is what OCANNL needs, a preprocessor that knows the types. Its notation for tensor code is a syntax extension, and in OCaml a syntax extension runs before type inference and cannot see what will be inferred. Rust’s macros run before the types are known too. MacoCaml would not supply the third thing either. Its authors call its macros “purely generative”: they build code and cannot take apart the code they are given. None of the three has anything to do with ownership.

So, plainly. As designs, neither contains the other: Rust reaches lower, and OCaml and OxCaml combine more freely. Wherever the runtime, the platform, the libraries or the promise of stability decides, Rust is better, and those decide often. For a program that is already OCaml and needs control in a few places, OxCaml is better, if one can live on one firm’s schedule.

Part II. Laws

Curious OCaml is a textbook of functional programming whose programs run each time it is built. Where OCaml’s types cannot keep a promise that the code makes, the book keeps it at run time or by a test, and Part I followed three such promises about ownership through OxCaml, Rust and Lean.

The fourth promise is of another kind. The first three were about how a value is used. The fourth is about what a module does: that a map which has just been given a key will return it, that deleting a key leaves the others alone. The book writes such laws down and tests them.

What the book tests

Chapter 4 builds maps several ways and then writes one suite for all of them. The suite takes any module M with the signature of a map. Its center is a function that asserts the map axioms for one map m. In it, find_opt is find with a failed lookup turned into None.

let check m =                   (* The axioms, for one map m. *)
  List.iter (fun k ->
    assert (M.member k m = (find_opt k m <> None));
    let added = M.add k "new" (M.add k "old" m) in
    assert (M.member k added);
    assert (find_opt k added = Some "new");
    assert (not (M.member k (M.remove k added)));
    assert (find_opt k (M.remove k added) = None);
    List.iter (fun j ->
      if j <> k then begin      (* Other keys are undisturbed. *)
        assert (M.member j (M.add k "new" m) = M.member j m);
        assert (M.member j (M.remove k m) = M.member j m);
        assert (find_opt j (M.add k "new" m) = find_opt j m);
        assert (find_opt j (M.remove k m) = find_opt j m)
      end) keys) keys

The suite calls check on every map that can be built from the empty one by at most three additions and removals of three keys. The chapter then says what that is worth:

What have we established? The three implementations agree with the axioms on a few hundred small maps over three keys. That is evidence, not proof, and it has blind spots […] A proof has a different structure. State the invariant of the representation (unique keys; the search-tree ordering), show that empty satisfies it and that add and remove preserve it […]

An invariant is a property that every value of the representation has and every operation keeps. The book describes the proof and does not give it. OCaml is the wrong place to give it. As Dependent Types from Rocq to Lean 4 explains, an OCaml type is a weaker claim than a proposition, because every OCaml type is inhabited by a program that loops or raises.

Lean 4 is a language in which the proof can be written next to the program and checked by the same tool. We asked an agent for the proof the chapter describes.

It ported the binary search tree of Chapter 4 to Lean: the type, member, find, add, remove and its helper, 44 lines. Here is add as the book has it, and then as ported.

let rec add k v m =
  match m with
  | Empty -> T (Empty, k, v, Empty)
  | T (m1, k2, _, m2) when k = k2 -> T (m1, k, v, m2)
  | T (m1, k2, v2, m2) when k < k2 -> T (add k v m1, k2, v2, m2)
  | T (m1, k2, v2, m2) -> T (m1, k2, v2, add k v m2)
def add (k : α) (v : β) : Tree α β → Tree α β
  | empty => node empty k v empty
  | node m1 k2 v2 m2 =>
    if k = k2 then node m1 k v m2
    else if k < k2 then node (add k v m1) k2 v2 m2
    else node m1 k2 v2 (add k v m2)

The agent stated the invariant, that the tree is ordered:

def Ordered : Tree α β → Prop
  | empty => True
  | node m1 k _ m2 =>
    Ordered m1 ∧ Ordered m2 ∧ AllKeys (· < k) m1 ∧ AllKeys (k < ·) m2

AllKeys P t says that every key of t satisfies P. The agent proved that empty is ordered and that add and remove keep a tree ordered. Then it proved every law the book’s suite asserts, for every ordered tree and not for a few hundred. The statements take 73 lines and the proofs 208. Lean’s checker was run ten times before all of it passed. Six of those runs failed. Each took about half a second.

No law had to be weakened. Three things had to be said that the OCaml leaves unsaid.

The first is the order on keys. OCaml compares keys of any type with a built-in <. Lean wanted a relation and its laws: that nothing is less than itself, that the relation is transitive, that two different keys are ordered one way or the other.

class StrictTotal (α : Type) [LT α] : Prop where
  irrefl : ∀ a : α, ¬ a < a
  trans : ∀ {a b c : α}, a < b → b < c → a < c
  total : ∀ {a b : α}, a ≠ b → ¬ a < b → b < a

The second is that a helper cannot fail where it is used. The OCaml split_rightmost raises Not_found on an empty tree, and remove calls it only on a tree that is not empty. In Lean the helper returns an optional result, and the proof has to show that the empty case does not arise.

The third is which equality is meant. With floating-point keys the book’s own law fails in OCaml: member nan (add nan 1 empty) is false, because the number nan is not equal to itself. The book knows this. Chapter 4 remarks on nan and says that it will test its maps with integer keys. The Lean version had to choose, and with the equality it chose everything equals itself and the answer is true. In OCaml the matter is a sentence in the text. In Lean it is part of the definition.

With add, Ordered and StrictTotal on the page, one of the proofs can be read whole. It shows that add keeps a tree ordered.

theorem ordered_add [StrictTotal α] {k : α} {v : β} :
    ∀ {t : Tree α β}, Ordered t → Ordered (add k v t)
  | empty, _ => ⟨trivial, trivial, trivial, trivial⟩
  | node m1 k2 v2 m2, ⟨o1, o2, a1, a2⟩ => by
    simp only [add]
    split
    · subst_vars; exact ⟨o1, o2, a1, a2⟩
    · split
      · exact ⟨ordered_add o1, o2, allKeys_add (by assumption) a1, a2⟩
      · exact ⟨o1, ordered_add o2, a1,
          allKeys_add (StrictTotal.total (by assumption) (by assumption)) a2⟩

The theorem is a function. It is given a tree and a proof that the tree is ordered, and it returns a proof that the tree with the key added is ordered. Like add, it is defined by cases on the tree, and like add it calls itself on a subtree. That call is the induction.

A proof that a node is ordered is four proofs, one for each clause of Ordered, and the pattern ⟨o1, o2, a1, a2⟩ takes it apart as it would a tuple. The book teaches that a pair is a proof of a conjunction, and here such a proof is handled as a pair. For the empty tree the result is a single node, and its four clauses hold trivially.

For a node, simp only [add] replaces add by its definition, so that what is to be proved contains the two ifs of add. A split divides the proof at an if into the case where the condition holds and the case where it does not, and records which. The first split is on k = k2 and the second on k < k2. Together they give the three branches of add, and each · begins one. If the new key is the one at the root, the four proofs serve as they are. If it is smaller, add goes left. The proof for the left subtree is then replaced by ordered_add o1, and a lemma proved earlier, allKeys_add, shows that the left subtree’s keys are still below the root once the new one is among them. The last case is the mirror image, and it needs the fact that the root’s key is below the new one. Neither split recorded that. They recorded that the two keys differ and that the new one is not the smaller, and StrictTotal.total turns those into the fact that is needed. It is the only place where this proof uses a law of the order. by assumption asks Lean to find a fact among those at hand, which here are the ones the splits recorded.

The proofs also found something that nobody had asked. The laws about add hold for every tree, ordered or not, and for every relation <, lawful or not. add and find walk down the same path, whatever the path is, and so find finds what add put there. Only the laws about remove need the invariant. The difference can be read off two statements:

theorem find_add_self (k : α) (v : β) (m : Tree α β) :
    find k (add k v m) = some v := by simp [find_add]

theorem find_remove_self [StrictTotal α] (k : α) {m : Tree α β} (hm : Ordered m) :
    find k (remove k m) = none := by simp [find_remove k k hm]

The second asks for a lawful order and for hm, a proof that the tree is ordered. The first asks for neither. The test suite could not show this, because it only ever builds ordered trees.

Lean also made one of the book’s programs say why it stops. Chapter 11’s Datalog engine applies its rules round after round until a round adds nothing. Written the same way in Lean, the loop is rejected: “fail to show termination”. A recursive function in Lean can be reasoned about only if Lean has a reason why it ends. Here the reason is that every round stays inside a finite set of possible facts, those that can be written with the program’s constants. The OCaml engine depends on that and never says it.

As a language to program in, Lean is nearer to OCaml than its reputation suggests, and in places ahead of it. Memory is managed by counting references. A value with a single owner is updated in place. OxCaml has a mode, unique, for values to which no other reference exists, and it is meant to give the same thing checked by the compiler. Lean has macros, and it has elaborators, which run inside the type checker and can ask for the type of the term they are building. An elaborator is the preprocessor that knows the types, which I miss in OCaml. In other places Lean is behind. Effects are monads, so Lean programs are written in the monadic style of the book’s Chapter 9 and not with the effect handlers of its Chapter 10. Its package index lists 955 packages, its interface to C is documented as unstable, and every release this year has broken something, with a promise that this is the last such year.

Is Lean simply better for an agent?

The case for it is stronger than it was a year ago.

One standard collection has 189 small programs to be written and proved in Lean. When it was published, the best model completed the proof for about one program in twenty. By this October an agent built around an ordinary frontier model settled all 189, each by a proof or by showing its statement false. At Microsoft, the cryptographic library SymCrypt now carries proofs of its Rust code, about 125,000 lines of them for 16,700 lines of Rust, mostly written by agents. Verifying one layer of one algorithm by hand had taken the team six months. A new algorithm now takes “about a week for an agent and a few days of human review”.

Our own bench agrees. The lecture the book grew from had a bug in its deletion from red-black trees. We asked for the corrected deletion to be proved to return a valid red-black tree. The proof is 380 lines for 58 lines of code, and the attempt that succeeded took under seven minutes of checking.

The case against has four difficulties, and the first is in that same episode. The agent’s first attempt took about 75 seconds of checking. It left three holes in the proof and reported that the rest was hard and that it had run out of time. Its log said otherwise. Claude, who was directing the work and reading the logs, sent it back, and it finished. Its second report says that its earlier judgment had been wrong. A proof assistant cannot be talked round. An agent’s account of what it did with the proof assistant can be wrong, like anyone’s.

The source file can mislead as the report did. When a Lean file has an error in it, Lean puts an unproved assumption in place of the proof that failed, and nothing in the file says so. A search of the source for the word that marks a gap finds nothing. The command that lists a theorem’s assumptions, #print axioms, shows it:

'BTree.find_remove' depends on axioms: [propext, sorryAx, Quot.sound]

sorryAx is the gap. The essay on dependent types said that this command tells what a theorem depends on. Here is a case where the source file does not.

The second difficulty is the statement. A checked proof establishes its statement, and whether the statement says what was meant is a separate question. The essay on dependent types put it as “A correct kernel can check an unintended theorem”, and Before the Search Settles said of a proof checker that “it certifies only the step from a formal statement to its proof.” This year those sentences acquired numbers. An audit of one collection of problems, whose statements had been written by people, found the reference statement arguably wrong in 80 of 161 cases. Agents asked to prove a statement will weaken it if they are allowed to. The harnesses that do well freeze the statement first, and the SymCrypt authors write that “careful human review of theorem statements remains essential.” Agents also edit tests to make them pass. On tasks built so that the tests could not honestly pass, one strong model got them to pass more than half the time. Weakening a theorem is the same move, one level up.

Our red-black theorem shows the gap in a harmless form. Its statement:

theorem fixed_remove_valid (k : Nat) (t : Tree) (h : valid t = true) :
    valid (Fixed.remove k t) = true

It says that deletion returns a valid red-black tree. It does not say that the tree holds exactly the other keys. That was proved for the plain search tree and not for this one.

The third difficulty is that a failed proof says less than a failed test. The lecture’s bug was found by a test that printed a counterexample: insert 1, 2 and 3, remove 1, and the tree is no longer valid. We asked what Lean says of the same broken code. Run as a program, Lean found the same counterexample in a millisecond. Asked for a proof that the broken deletion is correct, it stopped first at a goal that shows only that the proof is hard. After one more case split a goal read False, at the case the lecture’s code mishandles. To conclude that the statement was false still took a witness. A test says no and hands over an input. A proof says yes. An agent needs both.

It goes the other way too. For the corrected deletion, the first invariant the agent tried held on fifty thousand tested cases and was too weak to carry the induction. The proof found what the tests had not.

The fourth difficulty is the boundary. The red-black proof is about Lean code that an agent transcribed from the book’s OCaml, for keys that are natural numbers. Nothing proves that the transcription matches. And a proof covers the program up to the edge of the language. An audit of a compression library that agents had written and proved in Lean ran it more than a hundred million times on generated input. It found no error in the proved code. It found two outside, one of them in the runtime system of Lean itself.

Where Lean is used in industry, it is seldom the language of the program. Amazon’s policy language Cedar keeps a model in Lean, proves theorems about the model, and tests the production code, which is Rust, against it. SymCrypt’s Rust is translated into Lean and proved there. Jane Street announced this June that it is building a team for formal methods, and is looking for ways to integrate such tools with OxCaml.

So is Lean simply better? No. As a language to write programs in, it is behind OCaml and Rust in its libraries, its stability and its interface to C. As the place where a program written elsewhere gets its proof, it has become affordable quickly.

In the memoir I called myself curious about guarantees beyond what a strict compiler gives, and not yet convinced. I can now say where my reservation lies. It is about building code that is verified from the start. The errors measured this year are in statements, and a statement written before the program has run has nothing to be checked against. What makes sense to me is the other order: to explore running code, and to update it with specifications that are insights into the problem. That add needs no invariant is, I think, an insight of this kind. It came from a proof, about code that already worked.

What an agent needs, and what I need from the agent

In the memoir I wrote that “agents and people benefit from the same things: strictness, and a compiler that checks every case is covered.” This section tests that sentence on what we have.

The book’s checks spoke to agents all through the making of this edition, and we took a count from the session’s logs. The edition was made in one working session by a main agent and thirty-two others. They ran the book’s checks 461 times, and the checks rejected 93 times.

What rejected Runs
A chapter whose executed output no longer matched its text 33
The compiler (the type checker in 16 of these) 21
A failure while running a test (a failed assertion in 10) 17
The build system 14
Other checks of the book 8

The median check answered in under a second. The median repair took two edits and twenty seconds.

We had expected the type checker to head that table. It does not. It may have prevented a great deal before any run, and a count of rejections cannot see that.

The account we started from also said that the book’s standing tests had found the edition’s defects. The logs say that mostly they did not. A pretty-printer that had been off by one for two editions was caught when an agent doubted it and wrote a throwaway program comparing it with a reference on 300,000 random documents. The red-black bug was suspected on reading the lecture notes and then pinned down by trying every order of insertion. In case after case an agent read something, doubted it, and wrote a probe. A probe of this kind typically ran in a third of a second. The tests in the book came afterwards, to fasten the fix down.

So the first thing these agents had was a loop fast enough to make doubt cheap. OCaml’s part in it is a compiler that answers in well under a second. An interpreted language would do as well on that point.

The second thing an agent needs is to know the language, and here OCaml is at a disadvantage. My own measure is the quality of a language’s code integrated over its amount. By amount OCaml is tiny: at most 0.003 percent of a standard training corpus. On one benchmark a strong model solved 52 percent of the problems in OCaml and 61 percent in Java, and imperative patterns appeared in four fifths of its OCaml. We found no measurement of the quality of a corpus. In the memoir I wrote that agents were good at OCaml early, more than they themselves believed. If quality counts as well as amount, that is what one would expect. It is an observation and no more.

The third thing is the one I most wanted to know. In the memoir I described what programming did to my own thinking. It gave me the habit of taking a problem apart into variables and their transitions, and the habit of asking what kinds of things there are and which fall under which. The second I learned from objects, where a class hierarchy is a claim about kinds. In a functional program the types make the same claim. Does the way types structure thinking apply to an agent?

The question has three senses, and the evidence differs for each.

A type can work as feedback: the checker rejects and the agent repairs. That is measured. In one study, on average 94 percent of the compile errors in models’ TypeScript were type errors, and the table above is our own count.

A type can work as a plan that is held while writing. A signature in view narrows what is written next, and a declared type with five cases asks for five branches. There are measurements of this too, when the constraint is applied from outside: forcing a model’s output to be well typed as it is produced halves its compile errors and raises the share of correct programs. What Should a Program Inherit? reports a result of the same kind, for a system whose output is well typed by construction.

And a type can work as a habit, carried into places where nothing enforces it. For that we had no evidence, so we ran an experiment, and then at my request ran it again in two more languages.

The task was a small Datalog interpreter, from a precise specification, with eighty hidden tests. Agents were told one of two things. Half were told to work types first: to write down the kinds of things in the problem as types, and an interface for every module, and to check those before writing anything else. Half were told nothing about method. There were eight agents in each group, with two models in OCaml and one in TypeScript and Python. Afterwards each program written by the faster model was handed to a fresh agent, under a name that did not reveal its origin, with an extension to implement. We wrote down what we expected before any of it ran.

The main result is that nothing happened. In OCaml, both groups wrote a correct interpreter of about four hundred lines, the faster model in about a minute, at the same cost, and nearly every program passed all eighty tests. Correctness was the same in TypeScript and in Python. The task was too easy to show a difference, in any of the three languages, under either instruction.

What differed was the shape of the programs, and what the next agent did with it.

OCaml TypeScript Python
How terms were represented, with no instruction a variant type a tagged union tuples with a tag in front
How the four kinds of error were represented, with no instruction strings strings strings
The same, when told to work types first a variant type, in 14 of 16 a union of literals strings
Whether a type checker ran, with no instruction always always never

Here is how one uninstructed program in each language declared its terms.

type term = Const of value | Var of string | Anon
type Term = { t: "c"; v: string } | { t: "v"; name: string } | { t: "a" };
# term: ("c", value) | ("v", name) | ("_", None)

The Python declaration is a comment. And here are the kinds of error, in programs whose agents were told to work types first:

type category =
  | Parse
  | Arity
  | Unsafe
  | Unstratifiable
export type ErrorCategory = "parse" | "arity" | "unsafe" | "unstratifiable";

The Python programs kept strings.

In these runs the precise type appeared unasked where the language made it cost one line, and nowhere else. That was so for the terms of the language, in OCaml and in TypeScript. For the kinds of error, nobody wrote a type until asked, and in Python not even then.

The extenders are the clearest result. In all 64 extensions across the three languages, the agent wrote to the representation it found. Where the errors were a type, it added a case to the type. Where they were strings, it added a string. Nobody told it to. An agent is a reader too. It has a bounded memory, it forgets between sessions, and it hands work to other agents that start with nothing. The types in a program are part of what it reads, and it does what they suggest.

Two cautions came out of the same runs.

Only one OCaml extension introduced a bug. The agent added a case to a type and wrote a comparison that did not cover it. OCaml warns about exactly that. But the agent that had written the original program, one of those told to work types first, had put a flag in its build script, -w -a, that turns all warnings off, and so had two others of its group. The check that types-first is for was there, and an agent had switched it off. It is the same move as writing any, the TypeScript type that turns checking off, which agents add nine times as often as people, or as weakening a theorem. A check helps an agent only while it stays on, and these agents switched checks off when that was easy. I wrote in The Ledger of Mistakes that a typed language is an extraordinary ally and not an oracle. So the memoir’s sentence needs a rider. A compiler that checks every case is covered helps an agent as it helps a person, provided the agent cannot quietly tell it to stop.

The other caution is against reading too much into the result. Nothing in these experiments shows that OCaml’s types made agents more correct. The failures that differed between the languages had nothing to do with variants, and there were too few of them to be sure the languages differ at all. The specification said that strings are sequences of bytes. A third of the Python and TypeScript extensions read them as text in one encoding and wrote them out in another. An OCaml string is a sequence of bytes, so there was nothing to get wrong. No type checker in any of the three languages would have caught the mistake, since both sides of it are called a string.

Others report more than we measured. Jane Street writes that in its own work “agents benefit a ton from universal guarantees”, meaning guarantees such as freedom from data races that hold for every program the compiler accepts. That is a report from practice, without numbers.

Claude adds, in its own voice. I can say what something like a type did in the work behind this essay, without deciding whether it should be called thinking. Claims in our research notes carried labels: read at the source, reported second-hand, inferred, or remembered. The list of the edition’s defects came from another session, and the rows I could not find in the book I labelled second-hand. That label is one reason the list was checked against the logs. The check overturned more than those rows: the standing tests had not found the defects. A label of that kind is a type on a sentence. It did not make me right. It marked which of the things I believed had not yet been made to answer to anything.

What do I need, then, as the one who reads? I no longer write the code. It would be convenient if the part that must be read were small and the part a machine checks were large. It is not so simple. What a program is meant to do can seldom be said in much less space than the program. The search tree is 44 lines, and its laws took 73 to state. The proofs are another matter. They are long, and they are the machine’s to read.

Where a program is long for the sake of how it runs, the laws about what it computes stay short: one suite of map axioms serves the book’s list of pairs and its red-black tree alike. That suite says nothing about speed, and the book notes that it “would be just as satisfied with a red-black tree whose colors were wrong”. A law about how the program runs can be as loose or as exact as one likes. A bound on the depth of the tree would fit any balanced tree. The rule about colors fits this one. The closer a law follows the algorithm, the less it saves. Laws, like tests, need not shorten the meaning. They give another way into it, in pieces that can each be read alone and that a machine holds the program to.

In OCaml those pieces are an interface file and a suite of laws, and the check takes five seconds. OxCaml lets a little more be said in the interface, and Part I showed the price falling on every client and library. Lean lets a theorem be read in place of a test, provided someone reads the theorem.

Where the four are going

Here is the comparison in one place.

Checks before the program runs Leaves to run time or to tests What it charges
OCaml types, exhaustive matching, module interfaces scope, single use, races, laws little to write; a small corpus and ecosystem
OxCaml the same, and scope, single use and races where asked dropped continuations, laws annotations that spread to clients and libraries; one firm, no stability
Rust scope, single use, races, aliasing forgotten destructors, laws ownership decided everywhere; no collector, no effect handlers
Lean 4 whatever is stated and proved whatever is not stated; the runtime the statement and its reading; a young ecosystem

The four are moving toward one another. Lean’s current roadmap lists stack allocation and uniqueness annotations for its compiler, which is OxCaml’s ground. Jane Street is building a team for proofs, which is Lean’s. Rust programs are proved in Lean. And the organization behind Lean describes a project in which “we write the specifications, and AI agents implement both the executable code and the formal proofs.”

The book’s comment said that the callback owns the resource scope. In OxCaml that sentence is a mode in a signature, in Rust the default, in Lean a reference count. In the book it stays a comment and a flag, where a reader can watch the promise being kept by hand.

The experiments were run on 28 and 29 November 2026 with OCaml 5.5.1, OxCaml 5.4.0+ox, Rust 1.100.1 and Lean 4.36.0, by agents working under Claude’s direction at my request. Their sources, logs and results are in the site’s repository under notes/research/curious-ocaml-postscript-experiments: the scoped reader and the continuation in four languages (A), the proofs in Lean (B), the count from the edition’s logs (C), and the two experiments on writing types first (D and E), each with what was predicted beforehand. The research behind the comparisons, with sources, is in the dossier beside them.