问题
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!
回答1:
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
回答2:
Dire will do precisely this. All precondition predicates are invoked before the function is evaluated. If the predicates all return true, the function evaluates. Otherwise an exception is raised. Evaluation of all postcondition predicates follows.
来源:https://stackoverflow.com/questions/10778539/clojure-pre-post-functions