Skip to content

Instantly share code, notes, and snippets.

@Octachron
Created July 10, 2021 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Octachron/355ae3daf56065f97af7279a11021979 to your computer and use it in GitHub Desktop.
Save Octachron/355ae3daf56065f97af7279a11021979 to your computer and use it in GitHub Desktop.
type msg = ..
type query_answer =
| Accepted
| Unknown
let printer_registry: (Format.formatter -> msg -> query_answer) list ref = ref []
let register_printer x = printer_registry := x :: !printer_registry
let print ppf msg =
let rec find msg = function
| [] -> Format.fprintf ppf "[unknown message]"
| p :: q -> match p ppf msg with
| Accepted -> ()
| Unknown -> find msg q
in
find msg !printer_registry
type msg += Int of int
type msg += Float of float
let int_printer ppf = function
| Int x -> Format.fprintf ppf "[%d]" x; Accepted
| _ -> Unknown
let float_printer ppf = function
| Float x -> Format.fprintf ppf "[%g]" x; Accepted
| _ -> Unknown
let () = List.iter register_printer [int_printer; float_printer]
let () =
let newline ppf _ = Format.pp_print_cut ppf () in
Format.printf "@[<v>%a@]@."
(Format.pp_print_list ~pp_sep:newline print) [Int 1; Float 2.5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment