Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml - Lazy.force

Is my map function in:

type 'a stream = Cons of 'a * 'a stream Lazy.t

let rec ones = Cons(1, lazy(ones));;

let rec map (f:'a -> 'b) (s:'a stream) : 'b stream =
  match s with
  |Cons(h,t) -> Cons(f h, lazy (map f (Lazy.force t)));;
;;

Correct? Would Lazy.forcing it like that already make it memoized?

like image 482
Secret Avatar asked Aug 23 '13 10:08

Secret


People also ask

What is lazy in OCaml?

Laziness is a restricted form of mutability and, like any other mutability, it complicates things when parallel computations come into play. In OCaml implementation, lazy values are not only changing their value throughout time but also type and representation.

Does OCaml use lazy evaluation?

In OCaml, the value of the conditional test if true then e1 else e2 is the value of e1 , and e2 is never evaluated. Similarly, the value of if false then e1 else e2 is the value of e2 , and e1 is never evaluated. This is called lazy evaluation .


1 Answers

Yes, it is correct.

Note however that there will be no sharing of computation when applying it on a regular/cyclic instead of infinite datastructure (as ones here). Forcing the N first elements of map succ ones will still apply succ N times. (There is actually some research work on languages that would allow to detect such form of regularity/cycles and make strict mapping on them terminate, see e.g. the CoCaml project.)

like image 147
gasche Avatar answered Nov 15 '22 10:11

gasche