Hi George,

> Once again, I make a globally referenced, infinitely long stream.  But
> now I use "lazy-seq"
> instead of "cycle":
> 
>    user=> (def ev-stream (lazy-seq (cons true (cons false ev-
> stream))))
>    #'user/ev-stream
>    user=> (defn ev? [n] (nth ev-stream n))
>    #'user/ev?
>    user=> (time (ev? 9876543210))
>    "Elapsed time: 47244.061 msecs"
>    true
> 
> OMG! Not only did it NOT hose the heap and crash, it actually ran much
> faster than the version
> with the unreferenced "(cycle [true false])".

The consing version of ev-stream is self-referential, because you explicitly 
made it so by consing it back onto itself. So it only has two items in it, 
though it bounces back and forth between them forever. The cycling version is 
not self-referential.

> The only reason I can think of, for this to NOT exhaust memory, is
> that the lazy-seq macro knows
> when to construct a circular list. Is that what happens?  If so, why
> DOESN'T it happen with "cycle",
> where it's obviously the behavior one would want?

cycle actually calls lazy-seq.  A quick way to check such things at the REPL is 
with source:

user=> (source cycle)
(defn cycle
  "Returns a lazy (infinite!) sequence of repetitions of the items in coll."
  {:added "1.0"
   :static true}
  [coll] (lazy-seq 
          (when-let [s (seq coll)] 
              (concat s (cycle s)))))

<snip>

> Now I'll test it with 9876543210, a number which "ev?" was able to
> handle:
> 
>    user=> (time (mod3 9876543210))
>    "Elapsed time: 37759.615 msecs"
>    1
>    user=> (mod 987654321 3)
>    0
> 
> Whoa! The computation finished in reasonable time, but with the WRONG
> answer! How did that happen?
> Did I find a bug?

No, there is simply a typo in your input arg.

Stu


Stuart Halloway
Clojure/core
http://clojure.com

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to