Created
September 1, 2011 10:15
-
-
Save ypsilon-takai/1185886 to your computer and use it in GitHub Desktop.
Creates memoised function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; | |
;; create memoised func | |
;; | |
;; momoize in clojure 1.2 and after does not work as I expected. So, I created this macro. | |
(defmacro defn-memo | |
"Creates memoised function. | |
Also creates: | |
accessor of the memoized data which named <fname>-data. | |
resetter of the memoized data which named <fname>-crear." | |
[fname arg-list & body] | |
`(let [mem# (atom {})] | |
(defn ~(symbol (str (str fname) "-data")) [] | |
@mem#) | |
(defn ~(symbol (str (str fname) "-clear")) [] | |
(reset! mem# {})) | |
(defn ~fname ~arg-list | |
(if-let [e# (find @mem# ~arg-list)] | |
(val e#) | |
(let [ret# ~@body] | |
(swap! mem# assoc ~arg-list ret#) | |
ret#))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment