Clojure: pre post functions

一笑奈何 提交于 2019-12-14 00:16:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!