Mamoize (function that returns a function)


/ Published in: Lisp
Save to your folder(s)

A nice example of a function that returns another function.


Copy this code and paste it in your HTML
  1. (defn memoize
  2. [function]
  3. (let [cache (ref {})]
  4. (fn [& args]
  5. (or (@cache args)
  6. (let [result (apply function args)]
  7. (dosync
  8. (commute cache assoc args result))
  9. result)))))
  10.  
  11. (def slowly (memoize (fn [x] (. Thread sleep 100) x)))
  12. (time (slowly 1))
  13. (time (slowly 1))
  14.  
  15. (def mri (memoize (remove-if f lst)))
  16. (time (mri odd? (range 1000)))
  17. (time (mri odd? (range 1000)))
  18.  
  19. ;; This may show an more dramatic speed-up
  20. (time (doall (mri odd? (range 11000))))
  21. (time (doall (mri odd? (range 11000))))

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.