If we have tree recursive procedure such as the follows, how can we
use memoize it so that it automatically caches the values it has
already computed .....

(defn fib [n]
  (println "Calling fib with arg --> " n)
  (cond
   (= n 0) 0
   (= n 1) 1
   :else (+ (fib (- n 1))
            (fib (- n 2)))))


I changed the source for memoize - added two print statements
(defn memoize
  "Returns a memoized version of a referentially transparent function.
The
  memoized version of the function keeps a cache of the mapping from
arguments
  to results and, when calls with the same arguments are repeated
often, has
  higher performance at the expense of higher memory use."
  {:added "1.0"}
  [f]
  (let [mem (atom {})]
    (fn [& args]
      (println "Calling memoized fn with args ->" args)
      (if-let [e (find @mem args)]
        (do (println "taking from cache"(val e)  )(val e) )
        (let [ret (apply f args)]
          (swap! mem assoc args ret)
          ret))) ))


Now memoizing and calling the function .....
(defn m-fib (memoize fib))

In this case, the INTERMEDIATE  values the function computes are NOT
stored in the memoize cache.

The only way I can think of of utilizing the memoize function as such
is as follows:

(defn fib2 [my-fun n]
  (println "Calling fib with arg --> " n)
  (cond
   (= n 0) 0
   (= n 1) 1
   :else (+ (my-fun my-fun  (- n 1))
            (my-fun my-fun   (- n 2)))))

(def m-fib2 (memoize fib2))
(m-fib2 m-fib2 10)


--------------------------------------------------------------------------------

Maybe memoize should go the same way as the contrib trace package -
i.e, have special macros. "Functional" memoizing can only cover so
much .........

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