You should make a LazySeq to momoize intermediate result:

(defn fib[n]
  (if (> n 2)
    (+ (fib (- n 2)) (fib (- n 1)))
    1))
(def fib (memoize fib))
(def fib-seq (map fib (iterate inc 0)))

then take the result by nth:

user=> (nth fib-seq 45)
1134903170
user=> (nth fib-seq 46)
1836311903
user=> (nth fib-seq 47)
2971215073

The only problem is that the fib-seq would cosume more memories to
hold  intermediate result.

On Jul 22, 5:47 am, logan <duskli...@gmail.com> wrote:
> 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?
>
> Using the default memoize does not work correctly. the reason is even
> though the first call to fib is memoized, the recursive calls go to
> the original fib, and not the memoized function.
>
> Even using
>
> (def fib (memoize fib))
>
> does not seem to work. if you run (fib 45) and (fib 46), in the ideal
> case, (fib 47) should just call the memoized (fib 45) and (fib 46) and
> return almost immediately, but that is not the case.

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