I wonder if any of the Clojurians on here might like to describe how one might write the factorial function as a parallel one? Taking advantage of the associativity of multiplication, along the lines of
16! = (((1*2)*(3*4)) * ((5*6)*(7*8))) * (((9*10)*(11*12)) * ((13*14)* (15*16))) On Jul 24, 8:38 pm, Daniel Lyons <fus...@storytotell.org> wrote: > Jeremy, > > On Jul 24, 1:20 pm, Jeremy Gailor <jer...@infinitecube.com> wrote: > > > I'm just looking for general optimizations that I should be aware of, the > > nature of the function itself isn't really important. I could turn to > > number theory to get some performance improvement, but from a Clojure > > oriented perspective, what things might I try? > > You are probably already know about this, but a good general > technique > is to rephrase your function with accumulators. For > example, > factorial, you might try to do it like > this: > > (defn fac > [n] > (* n (recur (- n > 1)))) > > This blows up because the recur isn't in the tail position. If > you > just change it to 'fact then your function will consume stack and > not > run as quickly as a naive loop. This can be rephrased using > an > accumulator like > so: > > (defn > fac > ([n] (fac n > 1)) > ([n acc] (if (zero? n) > acc > (recur (dec n) (* acc > n))))) > > Not quite as pleasing to the eye, but performs much > better. > > You can do this with multiple accumulators too, such as for > average: > > (defn > avg > ([l] (avg l 0 > 0)) > ([l cnt > tot] > (if (empty? l) (/ tot > cnt) > (recur (rest l) (inc cnt) (+ (first l) > tot))))) > > There's no need for this in Clojure though, because 'count is O(1), > so > this really can't perform any better than > this: > > (defn avg > [l] > (/ (reduce + l) (count > l))) > > Specifically to Clojure I would try and use laziness to my > advantage > as much as > possible. > > If you have the ability to turn to number theory I would > definitely > recommend > it. :) > > -- > Daniel (Stirling's Approximation to the factorial <http://en.wikipedia.org/ wiki/Stirling's_approximation>, useful in science) --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---