在不运行函数的情况下检查Clojure前提条件? [英] Checking Clojure pre-conditions without running the function?
问题描述
我有一个函数可以执行某些(可能是冗长的)工作(defn workwork [x] ...)
和其他一些函数来检查调用是否会成功时间(defn workwork-precondition-1 [x] ...)
。
I have one function that does some (possibly lengthy) work (defn workwork [x] ...)
and some other functions to check if the call will succeed ahead of time (defn workwork-precondition-1 [x] ...)
.
前提条件函数应为每次调用 work
(例如,使用:pre
)进行评估。前提条件函数也应该在一个函数中收集(和编辑),并直接提供给客户端代码(例如,禁用按钮)。
The precondition functions should be evaluated every time workwork
is called (e.g. using :pre
). The precondition functions should also be collected (and:ed) in a single function and made available to client code directly (e.g. to disable a button).
惯用语避免代码重复的同时在Clojure中解决此问题的方法?
Which is the idiomatic way to solve this in Clojure while avoiding code duplication?
特别是,有什么方法可以在不运行函数主体的情况下评估函数的前提条件吗?
In particular, is there any way to evaluate the pre-conditions of a function without running the function body?
推荐答案
您只需将前提条件收集到一个函数中即可:
You can just collect your preconditions into a function:
(defn foo-pre [x]
(even? x))
然后在:pre
样式的前提条件:
Then call the function in a :pre
-style precondition:
(defn foo [x]
{:pre [(foo-pre x)]}
…)
使用 defn
引入的函数,您可以从Var:上的元数据中提取:pre
样式的前提条件>
For functions introduced using defn
, you can extract the :pre
-style preconditions from the metadata on the Var:
(-> #'foo meta :arglists first meta)
;= {:pre [(foo-pre x)]}
对于:arglists
这里有两个警告:
-
自动生成的
:arglists
条目元数据可能会被覆盖。覆盖:arglists
会导致上述有用的自动生成的元数据被丢弃。
The automatically-generated
:arglists
entry in the Var's metadata maybe be overridden. Overriding:arglists
results in the above kind of useful automatically-generated metadata to be thrown out.
上面的(->#'foo meta…)$返回的
或 {:pre [(foo-pre x)]}
值c $ c>表达式包含 foo-pre
作为文字 symbol –您有责任弄清楚它在 foo
的定义点。 (这可能或不可能-例如, foo
可以在顶级<$中包含 defn
c $ c> let letfn
形式,其中 foo-pre
是本地函数。 )
The {:pre [(foo-pre x)]}
value returned by the above (-> #'foo meta …)
expression contains foo-pre
as a literal symbol – it'd be your responsibility to figure out which function it referred to at foo
's point of definition. (This may or may not be possible – for example foo
could be defn
'd inside a top-level let
or letfn
form, with foo-pre
a local function.)
最后,匿名函数可以使用:pre
和:post
,但是目前没有从函数本身中提取它们的机制。
And finally, anonymous functions may use :pre
and :post
, but there is currently no mechanism for extracting them from the function itself.
这篇关于在不运行函数的情况下检查Clojure前提条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!