<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE message PUBLIC
  "-//MLarc//DTD MLarc output files//EN"
  "../../mlarc.dtd"[
  <!ATTLIST message
    listname CDATA #REQUIRED
    title CDATA #REQUIRED
  >
]>

  <?xml-stylesheet href="../../mlarc.xsl" type="text/xsl"?>


<message 
  url="2002/07/7bdd2cd1ec6a871bf26b6f7b867ebe6c"
  from="Damien Doligez &lt;damien.doligez@i...&gt;"
  author="Damien Doligez"
  date="2002-07-04T15:14:25"
  subject="Re:  [Caml-list] more on lazy lists"
  prev="2002/07/ef50109a30eeae2684c3e9dc0c9b6aeb"
  next="2002/07/f9169f3ec2d8758bc125264b2df6077c"
  prev-thread="2002/07/28b3e549729725806506571fb42b9c54"
  next-thread="2002/07/47ffc0354acdc6c8f3c1f074c19ba9d0"
  root="../../"
  period="month"
  listname="caml-list"
  title="Archives of the Caml mailing list">

<thread subject="Re:  [Caml-list] more on lazy lists">
<msg 
  url="2002/07/7bdd2cd1ec6a871bf26b6f7b867ebe6c"
  from="Damien Doligez &lt;damien.doligez@i...&gt;"
  author="Damien Doligez"
  date="2002-07-04T15:14:25"
  subject="Re:  [Caml-list] more on lazy lists">
</msg>
</thread>

<contents>
From: Michael Vanier &lt;mvanier@cs.caltech.edu&gt;


&gt;Now I understand why references are used internally for lazily evaluated
&gt;values; it's for memoization i.e. so that a particular value doesn't have
&gt;to be recomputed after it's been computed once.

This is the essence of lazy evaluation.


&gt;  I'm having an odd problem, though; consider this code:

[...]


Your "stream_map2" function is not lazy enough: it will unnecessarily
force the tail of the stream.  You need to write it as follows:


  let rec stream_map2 proc s1 s2 =
    match (s1, s2) with
      (Cons (x1, y1), Cons (x2, y2)) -&gt;
        Cons ((proc x1 x2), lazy (stream_map2 proc (Lazy.force y1)
                                                   (Lazy.force y2)))
    | _ -&gt; raise Invalid_operation

Note that the calls to Lazy.force are inside the argument of lazy.
There is the same problem in your "take" function.


&gt;let integers = 
&gt;  let rec ints () =
&gt;    Cons (1, lazy (add_streams ones (ints ())))
&gt;  in
&gt;  ints ()

Now it works, but it is very inefficient (quadratic complexity)
because you rebuild a new "ints" stream at each call to add_streams.
Better to do it this way:

  let rec integers =  Cons (1, lazy (add_streams ones integers));;


-- Damien
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners

</contents>

</message>

