Hi Rob, Appreciate it, I like the code and explanation, great!
Simon On Thursday, March 29, 2012 6:28:48 PM UTC+8, Rob Nagle wrote: > > You can reduce in one pass with a function that tracks both the sum > and the count. > > (defn avg [coll] > (apply / (reduce (fn [[sum n] x] [(+ sum x) (inc n)]) [0 0] coll))) > > This reduce function is somewhat unusual in that its arguments have > different forms. As a result, this one does require the initial-value > argument be used. It's set to [0 0] indicating the sum and count both > start at 0. The function then "consumes" the numbers in coll one at a > time, producing the running sum and count each time. Then we just > apply / to divide the sum by the count. > > On Mar 28, 9:18 pm, "simon.T" <simon.j....@gmail.com> wrote: > > The obvious way is like the following, which traverse the sequence 2 > times. > > Wondering what will be the efficient way... > > > > (defn avg [coll] > > (/ (reduce + coll) (count coll))) -- 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