On Jul 4, 4:37 pm, Daniel Lyons <fus...@storytotell.org> wrote:
> On Jul 4, 2009, at 6:04 AM, arasoft wrote:
> > Using a fairly recent 1.1 snapshot, I get an OutOfMemoryError for
> > this:
>
> > (defn fib-seq []
> > ((fn more [a b]
> > (lazy-seq (cons a (more b (+ a b)))))
> > 0 1)
> > )
>
> > (nth (fib-seq) 200000)
>
> > However, this works fine:
>
> > (defn xth [coll i]
> > (if (zero? i) (first coll) (recur (rest coll) (dec i))))
>
> > (xth (fib-seq) 200000)
>
> > Am I doing anything wrong, or is this a bug?
>
> You aren't doing anything wrong, it's just that recur is a local jump
> which creates no stack and calling a function recursively is not. In
> other words Clojure doesn't have built-in tail call elimination, but
> recur creates the same effect. (I actually prefer this behavior
> because it's easy to see where you're paying the penalty for recursion
> and where you aren't, unlike in OCaml, Scheme and Haskell, where it
> can be easy to get confused about which form is the final position.)
I don't think this explains it. It is a OutOfMemoryError not a stack
overflow. It is not a recursion problem. I think it is that nth hangs
on to the head of the lazy fib sequence, and therefor all the elements
including the big integers can not be garbage collected.
The xth function does not hang on to the head, and all the
intermediate elements can be garbage collected.
//Lennart Staflin
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---