Skip to content

Effect handlers as resumable exceptions

4 August 2026 ยท OCaml 5.4

OCaml 5 brought multicore domains and effect handlers. An effect looks like raising an exception, except the handler receives a continuation k as well: calling continue k v resumes the computation right where perform paused it, turning push-style traversal into a pull-style sequence without rewriting the caller.

open Effect
open Effect.Deep

let to_seq (type a) (f : (a -> unit) -> unit) : a Seq.t =
  let module M = struct
    type _ Effect.t += Yield : a -> unit Effect.t
  end in
  let yield x = perform (M.Yield x) in
  fun () ->
    match_with f yield
      { retc = (fun () -> Seq.Nil);
        exnc = raise;
        effc =
          (fun (type b) (eff : b Effect.t) ->
            match eff with
            | M.Yield v ->
                Some (fun (k : (b, _) continuation) ->
                  Seq.Cons (v, fun () -> continue k ()))
            | _ -> None)
      }

type 'a tree = Leaf | Node of 'a tree * 'a * 'a tree

let rec walk yield = function
  | Leaf -> ()
  | Node (l, x, r) ->
      walk yield l;
      yield x;
      walk yield r

let () =
  let t = Node (Node (Leaf, 1, Leaf), 2, Node (Leaf, 3, Leaf)) in
  let items = to_seq (fun yield -> walk yield t) |> Seq.take 2 |> List.of_seq in
  assert (items = [ 1; 2 ])

walk is ordinary recursive code over a binary tree, yet Seq.take 2 never visits the right subtree Node (Leaf, 3, Leaf): the continuation after the second yield is simply dropped. In OCaml, continuations are one-shot, so resuming runs on a lightweight fiber stack with no heap copying of frames.