Ocaml: Lazy Lists
lazy-evaluation, ocaml, stream
Solution
Using streams:
let f x = Stream.from (fun n -> Some (x * int_of_float (2.0 ** float_of_int n)))
or
let f x =
let next = ref x in
Stream.from (fun _ -> let y = !next in next := 2 * y ; Some y)
Using a custom `lazy_list` type:
type 'a lazy_list =
| Nil
| Cons of 'a * 'a lazy_list lazy_t
let rec f x = lazy (Cons (x, f (2*x)))
Problem
How can I make a lazy list representing a sequence of doubling numbers? Example: ``` 1 2 4 8 16 32 ```