Home     About     Download     Resources     Contact us

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

Browse thread
possible way to improve "lazy"
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2007-03-20 (18:50) From: Jeffrey Loren Shaw Subject: possible way to improve "lazy"
```Dear Caml team,

Please consider this suggestion for an improvement of how caml handles lazy
evaluation. First I give an example.

type 'a t = Cons of 'a Lazy.t * ('a t) Lazy.t | Nil

let cons a b = Cons (lazy a, lazy b)

Suppose I want to build the Fibonacci sequence using the above function,
cons.

# let fib =
let rec aux a b =
cons a (aux b (a+b))
in
aux 0 1;;
Stack overflow during evaluation (looping recursion?).

whereas

# let fib =
let rec aux a b =
Cons(lazy a, lazy (aux b (a+b)))
in
aux 0 1;;
val fib : int t = Cons (<lazy>, <lazy>)

After a while I realized that there is a stack overflow because calling cons
evaluates its arguments *before* making them. This causes the infinite loop.

Now suppose we have a function like the above cons. Because the b argument
is never used in an eager way in the function, couldn't the interpreter say
"oh, b should not be evaluated"? This would allow the first example of fib
work, which looks like it should work unless you know what's going on behind
the scenes.

The fix for now is to define cons as

let cons a b = Cons (a,b)

so that whatever calls cons is forced to make sure a and b are already lazy.

let fib =
let rec aux a b =
cons (lazy a) (lazy (aux b (a+b)))
in
aux 0 1

But this also forces the calling function to be less clear. I would prefer
to be able to write

let fib =
let rec aux a b =
cons a (aux b (a+b))
in
aux 0 1;;

and rest assured that Caml would understand that cons does not need its
arguments evaluated.

Cheers,
Jeff

```