Skip to content

Instantly share code, notes, and snippets.

@ypsilon-takai
Created September 1, 2011 10:15
Show Gist options
  • Save ypsilon-takai/1185886 to your computer and use it in GitHub Desktop.
Save ypsilon-takai/1185886 to your computer and use it in GitHub Desktop.
Creates memoised function.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 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