From: "Jeffrey Loren Shaw" <shawjef3@msu.edu>
To: caml-list@inria.fr
Subject: possible way to improve "lazy"
Date: Tue, 20 Mar 2007 14:50:02 -0400 [thread overview]
Message-ID: <E1HTjPH-00082g-6M@sys25.mail.msu.edu> (raw)
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
next reply other threads:[~2007-03-20 18:50 UTC|newest]
Thread overview: 4+ messages / expand[flat|nested] mbox.gz Atom feed top
2007-03-20 18:50 Jeffrey Loren Shaw [this message]
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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=E1HTjPH-00082g-6M@sys25.mail.msu.edu \
--to=shawjef3@msu.edu \
--cc=caml-list@inria.fr \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox