Skip to content

Instantly share code, notes, and snippets.

@rplevy
Last active February 15, 2022 21:06
Show Gist options
  • Save rplevy/91e2f8880dea60063e69548ed667cd51 to your computer and use it in GitHub Desktop.
Save rplevy/91e2f8880dea60063e69548ed667cd51 to your computer and use it in GitHub Desktop.
(defmacro persist-scope
"local scope -> atom"
[a]
`(do ~@(map (fn [v] `(swap! ~a assoc (keyword '~v) ~v))
(keys (cond-> &env (contains? &env :locals) :locals)))))
(def scope-atom (atom {}))
(let [foo 1] (persist-scope scope-atom))
@scope-atom => {:foo 1}
;; This could be useful too, possibly make debugging a little more seamless
;; because you can pretend to be in the same lexical environment without extra wrangling
;; NOTE: you might confuse yourself with this if you have let bindings shadowing other
;; let bindings and using them for stuff before they are shadowed
(defmacro with-scope [scope-map & body]
`(let [{:keys [~@(map symbol (keys scope-map))]} ~scope-map]
~@body))
(with-scope @scope-atom (prn foo)) => 1
;; more info here: https://twitter.com/rplevy/status/1492247491500118016?cxt=HHwWgMCo_f3Lw7UpAAAA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment