Skip to content

Instantly share code, notes, and snippets.

@lupuszr
Last active May 15, 2019 21:26
Show Gist options
  • Save lupuszr/de2ec581b4c7aee1f414ccac618997ce to your computer and use it in GitHub Desktop.
Save lupuszr/de2ec581b4c7aee1f414ccac618997ce to your computer and use it in GitHub Desktop.
type lazy_node_t('a) =
| Delayed(unit => 'a)
| Value('a)
| Exn(exn);
type lazy_t('a) = ref(lazy_node_t('a));
let lazy_from_fun = f => ref(Delayed(f));
let force = x_lazy =>
switch (x_lazy^) {
| Value(x) => x
| Exn(e) => raise(e)
| Delayed(f) =>
try (
{
let r = f();
x_lazy := Value(r);
r;
}
) {
| e =>
x_lazy := Exn(e);
raise(e);
}
};
/* Based on http://typeocaml.com/2014/11/13/magic-of-thunk-lazy */
/* Test */
let x = () => Js.log("test");
let k = lazy_from_fun(x);
force(k)
/* what you should use: */
/* https://caml.inria.fr/pub/docs/manual-ocaml/libref/Lazy.html */
let y = () => Js.log("test");
let p = Lazy.from_fun(y);
Lazy.force(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment