You're viewing version 1.2.0 of memoize. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

memoize

clojure.core

  • (memoize f)
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.

1 Example top

  • ;; First we define a function that presumably have some expensive computation.
    user=> (defn myfunc[a] (println "doing some work") (+ a 10))
    #'user/myfunc
    
    ;; Next we create a memoized version of the function.
    user=> (def myfunc-memo (memoize myfunc))
    #'user/myfunc-memo
    
    
    ;; The first time we call the function with a particular argument the
    ;; original function is invoked and the value is returned.  The next
    ;; time the function is called with the same argument the cached result
    ;; is returned and the original function is NOT called.
    
    user=> (myfunc-memo 1)
    doing some work
    11
    user=> (myfunc-memo 1)
    11
    user=> (myfunc-memo 20)
    doing some work
    30
    user=> (myfunc-memo 20)
    30
    
Log in to add / edit an example.

See Also top

  • 0
    clojure.core/delay

    Takes a body of expressions and yields a Delay object that will inv

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:5082 top

(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]
      (if-let [e (find @mem args)]
        (val e)
        (let [ret (apply f args)]
          (swap! mem assoc args ret)
          ret)))))
Vars in clojure.core/memoize: assoc defn fn if-let let swap! val
Used in 1 other vars defn-memo

Comments top

No comments for memoize. Log in to add a comment.