| 1 |
= Lazy |
| 2 |
|
| 3 |
In a lazy (or non-strict) language, the arguments to a function are |
| 4 |
not evaluated before calling the function. Instead, the arguments are |
| 5 |
suspended and only evaluated by the function if needed. |
| 6 |
|
| 7 |
<<StandardML#,Standard ML>> is an eager (or strict) language, not a lazy |
| 8 |
language. However, it is easy to delay evaluation of an expression in |
| 9 |
SML by creating a _thunk_, which is a nullary function. In SML, a |
| 10 |
thunk is written `fn () \=> e`. Another essential feature of laziness |
| 11 |
is _memoization_, meaning that once a suspended argument is evaluated, |
| 12 |
subsequent references look up the value. We can express this in SML |
| 13 |
with a function that maps a thunk to a memoized thunk. |
| 14 |
|
| 15 |
[source,sml] |
| 16 |
---- |
| 17 |
signature LAZY = |
| 18 |
sig |
| 19 |
val lazy: (unit -> 'a) -> unit -> 'a |
| 20 |
end |
| 21 |
---- |
| 22 |
|
| 23 |
This is easy to implement in SML. |
| 24 |
|
| 25 |
[source,sml] |
| 26 |
---- |
| 27 |
structure Lazy: LAZY = |
| 28 |
struct |
| 29 |
fun lazy (th: unit -> 'a): unit -> 'a = |
| 30 |
let |
| 31 |
datatype 'a lazy_result = Unevaluated of (unit -> 'a) |
| 32 |
| Evaluated of 'a |
| 33 |
| Failed of exn |
| 34 |
|
| 35 |
val r = ref (Unevaluated th) |
| 36 |
in |
| 37 |
fn () => |
| 38 |
case !r of |
| 39 |
Unevaluated th => let |
| 40 |
val a = th () |
| 41 |
handle x => (r := Failed x; raise x) |
| 42 |
val () = r := Evaluated a |
| 43 |
in |
| 44 |
a |
| 45 |
end |
| 46 |
| Evaluated a => a |
| 47 |
| Failed x => raise x |
| 48 |
end |
| 49 |
end |
| 50 |
---- |