Return to Snippet

Revision: 17458
at September 5, 2009 17:22 by narkisr


Initial Code
(defn memoize
  [function]
  (let [cache (ref {})]
    (fn [& args]
      (or (@cache args)
          (let [result (apply function args)]
            (dosync
             (commute cache assoc args result))
            result)))))

(def slowly (memoize (fn [x] (. Thread sleep 100) x)))
(time (slowly 1))
(time (slowly 1))

(def mri (memoize (remove-if f lst)))
(time (mri odd? (range 1000)))
(time (mri odd? (range 1000)))

;; This may show an more dramatic speed-up
(time (doall (mri odd? (range 11000))))
(time (doall (mri odd? (range 11000))))

Initial URL
http://blog.fogus.me/2008/10/24/on-lisp-clojure-chapter-5/

Initial Description
A nice example of a function that returns another function.

Initial Title
Mamoize (function that returns a function)

Initial Tags
function

Initial Language
Lisp