Clojure: pre post functions

clojure

Solution

You could do this relatively easily with a higher order function:

(defn wrap-fn [function pre post]
  (fn [& args]
    (apply pre args)
    (let [result (apply function args)]
      (apply post (cons result args)))))

(def f
  (wrap-fn
    +
    #(println (str "Calling function with args: " %&))
    #(println (str "Returning with result: " (first %&)))))

(f 2 3)
Calling function with args: (2 3)
Returning with result: 5

Problem

Context I'm aware of http://blog.fogus.me/2009/12/21/clojures-pre-and-post/ What I want is not exactly pre/post conditions. I want to have pre/post functions that are executed exactly once. I don't see any documentation promising me this feature about the pre/post conditions (i.e. that they're not executed multiple times.) Question For a Clojure function, is there anyway to tag it with pre/post functions that are executed exactly once, - the pre function when the function is called - the post function when the function returns Thanks!

Original source