/ Published in: Lisp
A nice example of a function that returns another function.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
(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))))
URL: http://blog.fogus.me/2008/10/24/on-lisp-clojure-chapter-5/