Posted By

narkisr on 09/05/09


Tagged

function return clojure memoize


Versions (?)

Mamoize (function that returns a function)


 / Published in: Lisp
 

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

A nice example of a function that returns another function.

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

Report this snippet  

You need to login to post a comment.