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

Reply via email to