TExcelTAD
Home › OCaml › OCaml Effect Handlers

OCaml Effect Handlers

OCaml 5 introduced effect handlers, a powerful generalisation of exceptions. Like an exception, performing an effect jumps to a handler. Unlike an exception, the handler receives a continuation: it can resume the computation right where the effect was performed, with a value. This makes it possible to implement generators, lightweight threads, async I/O and dependency injection as plain libraries.

Effects live in the Effect module. This lesson uses the Effect.Deep handlers.

Declaring and performing an effect

An effect is declared by extending the type Effect.t. The type parameter is the type of the value the effect returns when resumed:

ocaml · try it yourself
open Effect
open Effect.Deep

type _ Effect.t += Ask_name : string Effect.t   (* performing it returns a string *)

let greet () =
  let name = perform Ask_name in
  Printf.printf "Hello, %s!\n" name

let () =
  try_with greet ()
    { effc = (fun (type a) (eff : a Effect.t) ->
        match eff with
        | Ask_name -> Some (fun (k : (a, _) continuation) -> continue k "Ada")
        | _ -> None) }
Hello, Ada!

Step by step:

  1. greet calls perform Ask_name. It does not know who will answer.
  2. Control jumps to the nearest handler for Ask_name, here installed with try_with.
  3. The handler's effc function is asked about each effect. For Ask_name it returns Some handler, which receives the continuation k.
  4. continue k "Ada" resumes greet with "Ada" as the result of perform.

The (type a) annotation is needed because each effect has its own result type (a GADT, see the previous lesson).

The same code, different handlers

Because the effect is just a request, different handlers can answer it differently. This is a clean form of dependency injection:

ocaml · try it yourself
open Effect
open Effect.Deep

type _ Effect.t += Log : string -> unit Effect.t

let process_order id =
  perform (Log (Printf.sprintf "start order %d" id));
  let total = id * 10 in
  perform (Log (Printf.sprintf "total %d" total));
  total

let with_console_log f =
  try_with f ()
    { effc = (fun (type a) (eff : a Effect.t) ->
        match eff with
        | Log msg -> Some (fun (k : (a, _) continuation) -> print_endline ("[log] " ^ msg); continue k ())
        | _ -> None) }

let with_collected_log f =
  let lines = ref [] in
  let result =
    try_with f ()
      { effc = (fun (type a) (eff : a Effect.t) ->
          match eff with
          | Log msg -> Some (fun (k : (a, _) continuation) -> lines := msg :: !lines; continue k ())
          | _ -> None) }
  in
  (result, List.rev !lines)

let () =
  let t = with_console_log (fun () -> process_order 7) in
  Printf.printf "result %d\n" t;
  let t2, logs = with_collected_log (fun () -> process_order 3) in
  Printf.printf "result %d, %d log lines: %s\n" t2 (List.length logs) (String.concat " | " logs)
[log] start order 7
[log] total 70
result 70
result 30, 2 log lines: start order 3 | total 30

process_order is identical in both runs. Only the handler decides what logging means.

Generators from iterators

A classic use: turn any "iterate with a callback" function into a step-by-step generator. Here Yield suspends the traversal of a tree, and the handler collects the first few values and then stops without resuming the rest:

ocaml · try it yourself
open Effect
open Effect.Deep

type tree = Leaf | Node of tree * int * tree
type _ Effect.t += Yield : int -> unit Effect.t

let rec walk = function
  | Leaf -> ()
  | Node (l, v, r) -> walk l; perform (Yield v); walk r

let take_first n tree =
  let taken = ref [] in
  match_with walk tree
    { retc = (fun () -> List.rev !taken);
      exnc = raise;
      effc = (fun (type a) (eff : a Effect.t) ->
        match eff with
        | Yield v -> Some (fun (k : (a, _) continuation) ->
            Printf.printf "(visited %d) " v;
            taken := v :: !taken;
            if List.length !taken < n then continue k () else List.rev !taken)
        | _ -> None) }

let () =
  let t = Node (Node (Leaf, 1, Node (Leaf, 2, Leaf)), 3, Node (Node (Leaf, 4, Leaf), 5, Node (Leaf, 6, Leaf))) in
  let first3 = take_first 3 t in
  print_newline ();
  print_endline (String.concat " " (List.map string_of_int first3))
(visited 1) (visited 2) (visited 3) 
1 2 3

match_with takes three functions: retc for normal return, exnc for exceptions, and effc for effects. When the handler returns without calling continue, the rest of the walk never happens. A continuation may be resumed at most once. Simply dropping it, as here, is allowed; if the suspended code held resources (open files, locks), you would call discontinue k exn instead so its cleanup code runs.

A tiny cooperative scheduler

Effects can implement lightweight threads. Each task performs Yield_turn to let the others run; the scheduler keeps a queue of continuations:

ocaml · try it yourself
open Effect
open Effect.Deep

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

let run_all tasks =
  let queue = Queue.create () in
  let rec spawn task =
    match_with task ()
      { retc = (fun () -> next ());
        exnc = raise;
        effc = (fun (type a) (eff : a Effect.t) ->
          match eff with
          | Yield_turn -> Some (fun (k : (a, unit) continuation) -> Queue.push (fun () -> continue k ()) queue; next ())
          | _ -> None) }
  and next () = if not (Queue.is_empty queue) then (Queue.pop queue) () in
  List.iter (fun t -> Queue.push (fun () -> spawn t) queue) tasks;
  next ()

let worker name steps () =
  for i = 1 to steps do
    Printf.printf "%s step %d\n" name i;
    perform Yield_turn
  done

let () = run_all [ worker "A" 3; worker "B" 2; worker "C" 1 ]
A step 1
B step 1
C step 1
A step 2
B step 2
A step 3

This is roughly how concurrency libraries like Eio are built on OCaml 5.

Note: Effects are not yet tracked in function types, so an unhandled effect is a run-time error (Effect.Unhandled), like an uncaught exception.

Test yourself

What does a handler receive that an exception handler does not?

  1. The stack trace
  2. A continuation to resume the computation
  3. The source code
  4. A mutex

Given type _ Effect.t += Get : int Effect.t, what is the type of perform Get?

  1. unit
  2. int
  3. int Effect.t
  4. 'a

Which OCaml version introduced effect handlers?

  1. 4.0
  2. 4.14
  3. 5.0
  4. 3.12