Hi!

This is happening because you have integers saved to a global
variable.

(iterate inc 1) creates an infinite lazy seq.

Def-fing it to a global says 'Hey, i might want this later!' to
Clojure.

This means that as you take numbers from integers;
they get saved in memory rather than being garbage collected.

This is why you run out of memory.

You'll notice that this version:

(limited-reduce + (iterate inc 1) 1000000)

Runs (in a nice constant memory) even though yours (which almost
appears equivalent) will not!

In fact, even this version:
(limited-reduce + (iterate inc 1) 1000000000)
Runs in a nice constant space memory, although it takes a long time.

Nothing is wrong with the code, its that darn data!

If you are interested in this stuff, read about 'Haskell performance
tips'. A lot of people would make references to 'holding on to the
head' and such, and it would pretty much go 'whoooosh' right over /my/
head. Then I read a bit about how Haskell and how laziness there
worked, and it started to make sense.

Hope this helps,
-Jon


On Sep 18, 3:52 pm, Patrik Fredriksson <patri...@gmail.com> wrote:
> Hi!
>
> Could someone please help me understand why the following causes a
> java.lang.OutOfMemoryError: Java heap space for large n:s (100000
> works fine, 1000000 does not).
>
> (def integers (iterate inc 1))
>
> (defn limited-reduce [fn coll n]
>   (loop [c coll i n result 0]
>   (if (zero? i)
>     result
>   (recur
>     (rest c)
>     (dec i)
>     (fn result (first c))))))
>
> (limited-reduce + integers 100000)
>
> Many thanks!
>
> /Patrik
--~--~---------~--~----~------------~-------~--~----~
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