Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created May 11, 2018 12:20
Show Gist options
  • Select an option

  • Save jtpaasch/1cb7f9492429242dcb5c065ce8ad7c6f to your computer and use it in GitHub Desktop.

Select an option

Save jtpaasch/1cb7f9492429242dcb5c065ce8ad7c6f to your computer and use it in GitHub Desktop.
An example of deferred execution with thunks and hashtables (OCaml)
module Logs = struct
let hash : (string, string) Hashtbl.t = Hashtbl.create 256
let show_all = fun () ->
Printf.printf "- - - HASH CONTENTS:\n%!";
Hashtbl.iter (fun key value -> Printf.printf "- - - '%s': '%s'\n%!" key value) hash
let register_msg key value =
Printf.printf "- Registering '%s': '%s'\n%!" key value;
Hashtbl.add hash key value
let close key =
Printf.printf "- Closing: '%s'\n%!" key;
let value = Hashtbl.find hash key in
Printf.printf "- - Closed: '%s'\n%!" value
let close_all = fun () ->
Printf.printf "- Closing all.\n%!";
Hashtbl.iter (fun key _ -> close key) hash
end
let show s = Printf.printf "Showing: '%s'\n%!" s
let main () =
at_exit Logs.close_all;
Logs.show_all ();
Printf.printf "Starting\n%!";
Logs.register_msg "foo" "bar";
Logs.register_msg "biz" "baz";
Unix.sleep 1;
show "A message.";
show "Another message.";
Logs.show_all ()
let () = main ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment