Hi all,
I am working on the functional programming chapter for the book this
week, and I have been reviewing uses of loop/recur vs. lazy-cat/lazy-
cons in Clojure to come up with some guidelines.
Here is where I am: If your function creates/returns only atoms or
fixed size collections, loop/recur is fine. If it might return (or
internally create) variable/huge/infinite collections, use lazy-*.
To make this more concrete: If you buy these guidelines, then butlast
is incorrect. If you point it at something huge it consumes all of
memory:
(last (butlast (take 100000000 (iterate inc 0))))
-> java.lang.OutOfMemoryError: Java heap space
A lazy version works just fine:
(defn lazy-butlast [s]
(if (rest s)
(lazy-cons (first s) (allbutlast (rest s)))
nil))
(last (lazy-butlast (take 100000000 (iterate inc 0))))
-> 99999998
But I bet that isn't the whole story. What are the counterarguments in
favor of non-lazy butlast?
Cheers,
Stuart
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---