Skip to content

Instantly share code, notes, and snippets.

@triclops200
Last active January 4, 2016 18:29
Show Gist options
  • Save triclops200/8660510 to your computer and use it in GitHub Desktop.
Save triclops200/8660510 to your computer and use it in GitHub Desktop.
(defmacro defmem
[name parms & body]
(let [fname (gensym) memname (gensym)]
`(do (declare ~name)
(letfn [(~fname ~parms ~@body)]
(let [~memname (atom {})]
(defn ~name ~parms
(if (contains? @~memname ~parms)
(get @~memname ~parms)
(do (swap! ~memname assoc ~parms (~fname ~@parms))
(get @~memname ~parms)))))))))
(defmem fib
[x]
(if (<= x 1)
x
(+' (fib (- x 1)) (fib (- x 2)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment