4. $ cat test_ocaml.ml
let hoge = lazy 1 + 2
$ omake
*** omake: reading OMakefiles
*** omake: finished reading OMakefiles (0.01 sec)
- build . test_ocaml.cmi
+ ocamlfind ocamlopt -package oUnit -warn-error A -annot
-I . -c test_ocaml.ml
File "test_ocaml.ml", line 1, characters 11-17:
Error: This expression has type int lazy_t
but an expression was expected of type int
let hoge = (lazy 1) + 2
5. (* hogeは int lazy_t 型 *)
let hoge = lazy (1 + 2)
let rec map f s = lazy (match s with
| (lazy SSnil) -> SSnil
| (lazy (SScons(x, s))) -> SScons(f x, map f s))
6. $ cat test_ocaml.ml
let hoge = lazy (1 + 2)
let _ = print_int (Lazy.force hoge)
(* (Lazy.force hoge) は Int 型 *)
$ ./test_ocaml
3
7. $ cat test_ocaml.ml
let hoge = lazy (1 + 2)
let _ = match hoge with
| lazy i -> print_int i
$ ./test_ocaml
3
8. let plus (lazy m) (lazy n) = lazy (m + n)
let _ = let i = Lazy.force (plus (lazy 1) (lazy 2)) in
print_int i
9. fun lazy plus ($m, $n) = $m+n
fun plus (x, y) = $case (x, y) of ($m, $n) => force ($m+n)
(* plus : int lazy_t -> int lazy_t -> int lazy_t *)
let plus m n = lazy(match (m, n) with
| (lazy m, lazy n) -> m + n)
10.
11. datatype a StreamCell = NIL | CONS of a * a Stream
withtype a Stream = a StreamCell susp
type 'a cell = SSnil | SScons of 'a * 'a stream
and 'a stream = 'a cell Lazy.t
12. fun lazy ($NIL) ++ t = t
| ($CONS (x, s)) ++ t = $CONS (x, s ++ t)
let rec (++) t1 t2 = lazy (match (t1, t2) with
| (lazy SSnil, lazy t2) -> t2
| (lazy (SScons(x, s)), t2) -> SScons(x, s ++ t2))
13. fun lazy take (0, s) = $NIL
| take (n, $NIL) = $NIL
| take (n, $CONS (x, s)) = $CONS (x, take (n - 1, s))
let rec take n s = lazy (match (n, s) with
| (0, _) -> SSnil
| (_, lazy SSnil) -> SSnil
| (n, lazy (SScons(x, s))) -> SScons(x, take (n - 1) s))
14. fun lazy drop (n, s) =
let fun drop' (0, s) = s
| drop' (n, $NIL) = $NIL
| drop' (n, $CONS (x, s)) = drop' (n - 1, s)
in drop' (n, s) end
let drop n s = lazy (
let rec drop' n s = match (n, s) with
| (0, lazy s) -> s
| (_, lazy SSnil) -> SSnil
| (n, lazy (SScons(_, s))) -> drop' (n - 1) s
in drop' n s)
15. fun lazy reverse s =
let fun reverse' ($NIL, r) = r
| reverse' ($CONS (x, s), r) = reverse' (s, $CONS (x, r))
in reverse' (s, $NIL) end
let reverse s = lazy (
let rec reverse' s r = match (s, r) with
| (lazy SSnil, r) -> r
| (lazy (SScons(x, s)), r) -> reverse' s (lazy (SScons(x, r)))
in Lazy.force (reverse' s (lazy SSnil)))