At least in your particular case, replacing map with map2, defined below as
a small modification to a subset of map, seems to do the trick:

(defn map2 [f coll]
  (lazy-seq
   (when-let [s (seq coll)]
     (let [r (rest s)]
       (cons (f (first s)) (map2 f r))))))

(map2 count [(repeat 1e8 "stuff")])

I believe this is because the original definition of map, or the subset of
it below:

(defn map [f coll]
  (lazy-seq
   (when-let [s (seq coll)]
     (cons (f (first s)) (map f (rest s))))))

holds onto the head via needing to keep the value of "s" around throughout
the entire call to (f (first s)) in order to later make the call (map f
(rest s)).  In map2, the value of s is no longer needed by the time f is
called.

Andy

On Mon, Nov 10, 2014 at 7:48 PM, 'Matt Bossenbroek' via Clojure <
clojure@googlegroups.com> wrote:

>  Ran into an interesting problem today. In short, this works:
>
> (count (repeat 1e8 "stuff"))
>
> But this doesn't:
>
> (map count [(repeat 1e8 "stuff")])
>
> To be fair, given sufficient memory, it would eventually complete. (If the
> second example does work for you, change it to 1e10 or something higher).
>
> The first one works because nothing is holding on to the head of the seq.
> My assumption is that the second is eating memory because map still has a
> reference to the item being processed, while the call to count is causing
> it to be evaluated. Thus the whole seq is retained and we run out of memory.
>
> Is my guess correct? If so, is there a workaround for this?
>
> Thanks,
> Matt
>
>  --
> 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
> ---
> You received this message because you are subscribed to the Google Groups
> "Clojure" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to clojure+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
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
--- 
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to