Skip to content

Instantly share code, notes, and snippets.

@RutledgePaulV
Last active November 27, 2018 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RutledgePaulV/c088a63634e987c8c984bd218fc50f4c to your computer and use it in GitHub Desktop.
Save RutledgePaulV/c088a63634e987c8c984bd218fc50f4c to your computer and use it in GitHub Desktop.
A macro for memoization of a body of code based on the values of all referenced vars (implicit memoization key instead of explicit arguments). Probably a terrible idea.
(defmacro cached [& body]
(let [dependencies (transient #{})
resolved (walk/postwalk
(fn [form]
(if (symbol? form)
(if-some [resolved (resolve &env form)]
(when (var? resolved)
(conj! dependencies resolved)
(.toSymbol ^Var resolved))
form)
form))
`(do ~@body))]
`(let [vars# ~(persistent! dependencies)
inner# (memoize (fn [_#] (eval ~resolved)))]
(fn [] (inner# (mapv var-get vars#))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment