caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* possible way to improve "lazy"
@ 2007-03-20 18:50 Jeffrey Loren Shaw
  2007-03-20 21:53 ` Zheng Li
  2007-03-20 23:39 ` [Caml-list] " Daniel Bünzli
  0 siblings, 2 replies; 4+ messages in thread
From: Jeffrey Loren Shaw @ 2007-03-20 18:50 UTC (permalink / raw)
  To: caml-list

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 



^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2007-03-21  1:06 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2007-03-20 18:50 possible way to improve "lazy" Jeffrey Loren Shaw
2007-03-20 21:53 ` Zheng Li
2007-03-20 23:39 ` [Caml-list] " Daniel Bünzli
2007-03-21  1:06   ` Jeffrey Loren Shaw

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).