Skip to content

Instantly share code, notes, and snippets.

@fogus
Forked from Chouser/debug-wrap.clj
Created November 22, 2011 20:12
Show Gist options
  • Save fogus/1386781 to your computer and use it in GitHub Desktop.
Save fogus/1386781 to your computer and use it in GitHub Desktop.
(defn push-wrap [v wrap & args]
(alter-var-root v #(with-meta (apply wrap % args) {::orig %})))
(defn pop-wrap [v]
(alter-var-root v #(if-let [m (::orig (meta %))] m %)))
(defn post [orig post-printer]
(fn [& args]
(let [rtn (apply orig args)]
(post-printer orig rtn args)
rtn)))
(defn pre [orig pre-printer]
(fn [& args]
(pre-printer orig args)
(apply orig args)))
;;; demo:
(push-wrap #'+ post prn)
(apply + [5 10])
; #<core$_PLUS_ clojure.core$_PLUS_@5aefb0d2> 15 (5 10)
;=> 15
(push-wrap #'+ post (fn [f rtn args] (println "add called with" args ", returned" rtn)))
(apply + [5 10])
; #<core$_PLUS_ clojure.core$_PLUS_@5aefb0d2> 15 (5 10)
; add called with (5 10) , returned 15
;=> 15
(pop-wrap #'+)
(push-wrap #'+ pre (partial prn :pre-add))
(apply + [5 10])
; :pre-add #<core$_PLUS_ clojure.core$_PLUS_@5aefb0d2> 15 (5 10)
; add called with (5 10) , returned 15
;=> 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment