| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
type 'a node = |
| 12 |
| Nil |
| 13 |
| Cons of 'a * 'a t |
| 14 |
|
| 15 |
and 'a t = 'a node Lazy.t |
| 16 |
|
| 17 |
let empty = Lazy.from_val Nil |
| 18 |
|
| 19 |
let cons x s = Lazy.from_val (Cons (x, s)) |
| 20 |
|
| 21 |
let peek x : _ node = Lazy.force x |
| 22 |
|
| 23 |
let thunk f : _ t = Lazy.from_fun f |
| 24 |
|
| 25 |
let rec force s = match peek s with |
| 26 |
| Nil -> () |
| 27 |
| Cons (_, s) -> force s |
| 28 |
|
| 29 |
let force s = force s; s |
| 30 |
|
| 31 |
let is_empty s = match peek s with |
| 32 |
| Nil -> true |
| 33 |
| Cons (_, _) -> false |
| 34 |
|
| 35 |
let rec of_list = function |
| 36 |
| [] -> empty |
| 37 |
| x :: l -> cons x (of_list l) |
| 38 |
|
| 39 |
let rec to_list s = match peek s with |
| 40 |
| Nil -> [] |
| 41 |
| Cons (x, s) -> x :: (to_list s) |
| 42 |
|
| 43 |
let rec iter f s = match peek s with |
| 44 |
| Nil -> () |
| 45 |
| Cons (x, s) -> f x; iter f s |
| 46 |
|
| 47 |
let rec map_node f = function |
| 48 |
| Nil -> Nil |
| 49 |
| Cons (x, s) -> Cons (f x, map f s) |
| 50 |
|
| 51 |
and map f s = lazy (map_node f (peek s)) |
| 52 |
|
| 53 |
let rec app_node n1 s2 = match n1 with |
| 54 |
| Nil -> peek s2 |
| 55 |
| Cons (x, s1) -> Cons (x, app s1 s2) |
| 56 |
|
| 57 |
and app s1 s2 = lazy (app_node (peek s1) s2) |
| 58 |
|
| 59 |
let rec fold f accu s = match peek s with |
| 60 |
| Nil -> accu |
| 61 |
| Cons (x, s) -> fold f (f accu x) s |
| 62 |
|
| 63 |
let rec map_filter_node f = function |
| 64 |
| Nil -> Nil |
| 65 |
| Cons (x, s) -> |
| 66 |
begin match f x with |
| 67 |
| None -> map_filter_node f (peek s) |
| 68 |
| Some y -> Cons (y, map_filter f s) |
| 69 |
end |
| 70 |
|
| 71 |
and map_filter f s = lazy (map_filter_node f (peek s)) |
| 72 |
|
| 73 |
let rec concat_node = function |
| 74 |
| Nil -> Nil |
| 75 |
| Cons (s, sl) -> app_node (peek s) (concat sl) |
| 76 |
|
| 77 |
and concat (s : 'a t t) = |
| 78 |
lazy (concat_node (peek s)) |
| 79 |
|
| 80 |
let rec concat_map_node f = function |
| 81 |
| Nil -> Nil |
| 82 |
| Cons (x,s) -> app_node (peek (f x)) (concat_map f s) |
| 83 |
|
| 84 |
and concat_map f l = lazy (concat_map_node f (peek l)) |