Created
August 15, 2020 21:27
-
-
Save djtango/9a22c7a50338567c0292c65a0e054a8c to your computer and use it in GitHub Desktop.
capture function inputs and arguments for REPL debugging
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
(ns capture | |
"This is useful if you are debugging a dependency, for example") | |
(defmacro capture [fname atm] | |
`(alter-var-root | |
(var ~fname) | |
(fn [f#] | |
(fn [& args#] | |
(let [result# (apply f# args#)] | |
(swap! ~atm conj {:args args# | |
:result result#}) | |
result#))))) | |
(comment | |
(defn add [a b] (+ a b)) | |
(defn mult [n m] (reduce add 0 (repeat n m))) | |
(add 1 2) | |
;; => 3 | |
(mult 8 4) | |
;; => 32 | |
(def add-in+out (atom [])) | |
(capture add add-in+out) | |
(mult 5 3) | |
;; => 15 | |
@add-in+out | |
;; => [{:args (0 3), :result 3} {:args (3 3), :result 6} {:args (6 3), :result 9} {:args (9 3), :result 12} {:args (12 3), :result 15}] | |
;; beware of direct linking https://clojure.org/reference/compilation#directlinking | |
;; For example, trying to spy on clojure.string/split doesn't work: | |
(def split-inputs+outputs (atom [])) | |
(capture clojure.string/split split-inputs+outputs) | |
(clojure.string/split-lines "foo\nbar") | |
@split-inputs+outputs | |
;; EXPECT THIS | |
;; => [{:args ["foo\nbar" #"\r?\n"] :result ["foo" "bar"]}] | |
;; ACTUALLY GET | |
;; => [] ;; :sad-panda | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment