filter is lazy so it won't actually do the work unless the values are needed. To get a reasonable time, you need to use the result for some computation. Try something like this:
(defn sum-all [m] (reduce + (apply map + (vals m)))) (time (sum-all (separate-nums (range 10000)))) On Feb 9, 2012, at 5:12 PM, Manuel Paccagnella wrote: > Sorry for what I guess is a pretty basic question. I've written for practice > a simple function that takes a sequence of numbers and returns a map with the > odd and even ones. No big deal: > > (defn separate-nums [coll] > (hash-map :even (filter even? coll) :odd (filter odd? coll))) > > But I thought that I actually filter the same sequence two times (one for > taking out odd numbers and another one for even ones). So, why don't write a > "procedural" version and see how it compares to the functional one? > > (defn separate-nums-it [coll] > (loop [odd [] even [] nums coll] > (let [n (first nums)] > (if (nil? n) > (hash-map :even even :odd odd) > (if (even? n) > (recur odd (conj even n) (rest nums)) > (recur (conj odd n) even (rest nums))))))) > > Weeping for the second version, I wrote a quick&dirty timing test: > > (let [nums (range 65536)] > (do (time (separate-nums nums)) > (time (separate-nums-it nums)))) > > The output surprised me: > > "Elapsed time: 0.083074 msecs" > "Elapsed time: 51.026659 msecs" > > Following my previous reasoning, iterating over a sequence of numbers only > once should have been faster... What I'm missing? The iterative version is so > bad? I see that the filter function source code is much more complex than I > thought, so maybe there are important optimizations in there. -- 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