39348
|
1 |
(* ========================================================================= *)
|
|
2 |
(* SUPPORT FOR LAZY EVALUATION *)
|
39502
|
3 |
(* Copyright (c) 2007 Joe Hurd, distributed under the BSD License *)
|
39348
|
4 |
(* ========================================================================= *)
|
|
5 |
|
|
6 |
structure Lazy :> Lazy =
|
|
7 |
struct
|
|
8 |
|
|
9 |
datatype 'a thunk =
|
|
10 |
Value of 'a
|
|
11 |
| Thunk of unit -> 'a;
|
|
12 |
|
|
13 |
datatype 'a lazy = Lazy of 'a thunk ref;
|
|
14 |
|
|
15 |
fun quickly v = Lazy (ref (Value v));
|
|
16 |
|
|
17 |
fun delay f = Lazy (ref (Thunk f));
|
|
18 |
|
|
19 |
fun force (Lazy s) =
|
|
20 |
case !s of
|
|
21 |
Value v => v
|
|
22 |
| Thunk f =>
|
|
23 |
let
|
|
24 |
val v = f ()
|
|
25 |
|
|
26 |
val () = s := Value v
|
|
27 |
in
|
|
28 |
v
|
|
29 |
end;
|
|
30 |
|
|
31 |
fun memoize f =
|
|
32 |
let
|
|
33 |
val t = delay f
|
|
34 |
in
|
|
35 |
fn () => force t
|
|
36 |
end;
|
|
37 |
|
|
38 |
end
|