Skip to content

Instantly share code, notes, and snippets.

@craigfe
Created January 9, 2021 22:07
Show Gist options
  • Save craigfe/a11d06d7519c19553b3da2a2389de2e8 to your computer and use it in GitHub Desktop.
Save craigfe/a11d06d7519c19553b3da2a2389de2e8 to your computer and use it in GitHub Desktop.
(* Example due to @emillon. Mistakes my own. *)
type conf = { precision : int }
effect Get_conf : conf
let with_conf (conf: conf) ~f =
try f () with effect Get_conf k -> continue k conf
let get_precision () = (perform Get_conf).precision
type term =
| Float of float
| Plus of term * term
(* A pretty-printer for [term]s that supports dynamically-specified float precision. *)
let rec pp_term ppf = function
| Float f -> Format.fprintf ppf "%.*f" (get_precision ()) f
| Plus (a, b) -> Format.fprintf ppf "(%a) + (%a)" pp_term a pp_term b
let () =
let term = Plus (Float 1., Plus (Float 1., Float 1.)) in
with_conf { precision = 2 } ~f:(fun () ->
Format.printf "%a\n" pp_term term
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment