> Lets say I have the following function
>
> (defn fib[n]
> (if (> n 2)
> (+ (fib (- n 2)) (fib (- n 1)))
> 1))
>
> and I want to memoize it, what is the right way to do it?
Use defn-memo from clojure.contrib.def.
<mike
--
Mike Meyer <m...@mired.org> http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
O< ascii ribbon campaign - stop html mail - www.asciiribbon.org
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@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+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
On Thu, 22 Jul 2010 15:56:32 -0700 (PDT)
logan <dusk...@gmail.com> wrote:
> I tried defn-memo .. it still does not appear to memoize the original
> fib call? I tried this using clojure 1.2 beta. Reading the code
> definition for defn-memo it seems like it should work, but calling
> (fib 41) still takes a long time after calling (fib 40), when it
> should basically be an instantaneous call if the memoization works
> correctly.
Works fine on 1.1:
user> (defn-memo fib [n]
(println "Calling fib with arg --> " n)
(cond
(= n 0) 0
(= n 1) 1
:else (+ (fib (- n 1))
(fib (- n 2)))))
#'user/fib
user> (fib 40)
Calling fib with arg --> 40
[elided]
Calling fib with arg --> 0
102334155
user> (fib 41)
Calling fib with arg --> 41
165580141
user>
And yes, it's pretty much instantaneous. Possibly it's the same bug
that bit using the var in 1.2? Or maybe it's a different one.