If you only want to emulate non-strictness, then you only need to wrap the expression in a function and call it if necessary.
If you really want to imitate laziness (i.e. not rigor with memoization), then you need to wrap this function in a mutable link. Sketch in OCaml (ignoring exceptions):
type 'a lazy = 'a thunk ref and 'a thunk = Lazy of unit -> 'a | Memo of 'a let lazy f = ref (Lazy f) let force l = match !l with | Lazy f -> let x = f () in l := Memo x; x | Memo x -> x
Except that OCaml already has this predefined in its library (in a way that also handles exceptions from f).
Andreas Rossberg
source share