lazy_t
Last time: manipulating infinite data structures in lazyCaml
…
let rec nats n = n::(nats (n+1))
let rec trues = true::trues
Technically, streams simulate normal order evaluation (call-by-name) but not lazy evaluation, since there is no sharing…
OCaml has a built-in type ('a lazy_t
) for true lazy evaluation:
lazy : 'a -> 'a lazy_t (* lazy(e) is e wrapped for lazy evaluation *)
Lazy.force : 'a lazy_t -> 'a (* forces evaluation of a 'a lazy_t *)
type 'a lzlist = Nil | LzCons of 'a * ('a lzlist lazy_t)
let rec lznatp n =
let _ = printf "evaluated lznatp %d\n" n in
LzCons(n, lazy(lznatp (n+1)))
let rec lztake n ll = match (n,ll) with
| (0,_) | (_, Nil) -> []
| LzCons(h,t) -> h::(lztake (n-1) (Lazy.force t))
(* or: LzCons(h,lazy(t)) -> h::(lztake (n-1) t) *)
This also works for previous lazyCaml
examples:
let rec lz_dfs t =
let rec dfs t rst = match t with
| Empty -> Lazy.force rst
| Leaf v -> LzCons(v, rst)
| Node(l,r) -> dfs l (lazy (dfs r rst)) in
dfs t (lazy Nil)
Let’s double check that we’re making things faster…
cs2041.org