On Dec 9, 11:18 pm, Stuart Halloway <[EMAIL PROTECTED]> wrote:
> 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

I am assuming 'allbutlast' is 'lazy-butlast'.

Not really an in favor of butlast, but lazy-butlast also seems
much faster.

user=> (time (last (butlast (take 1000000 (iterate inc 0)))))
"Elapsed time: 2710.068764 msecs"
999998
user=> (time (last (lazy-butlast (take 1000000 (iterate inc 0)))))
"Elapsed time: 714.63721 msecs"
999998
user=> (time (last (butlast (take 1000000 (iterate inc 0)))))
"Elapsed time: 1832.329244 msecs"
999998
user=> (time (last (lazy-butlast (take 1000000 (iterate inc 0)))))
"Elapsed time: 710.971437 msecs"
999998
user=> (time (last (butlast (take 1000000 (iterate inc 0)))))
"Elapsed time: 1266.704242 msecs"
999998
user=> (time (last (lazy-butlast (take 1000000 (iterate inc 0)))))
"Elapsed time: 701.681986 msecs"
999998
user=> (time (last (butlast (take 1000000 (iterate inc 0)))))
"Elapsed time: 1712.931529 msecs"
999998
user=> (time (last (lazy-butlast (take 1000000 (iterate inc 0)))))
"Elapsed time: 694.106062 msecs"
999998
user=>

Parth

--~--~---------~--~----~------------~-------~--~----~
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
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to