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?
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.
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 .
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With