在特殊形式的 Clojure 文档中 ( http://clojure.org/special_forms )
条件映射参数描述如下:
The condition-map parameter may be used to specify pre- and postconditions for a function. It is of the following form:
{:pre [pre-expr*] :post [post-expr*]}
where either key is optional. The condition map may also be provided as metadata of the arglist.
我可以将条件映射作为一个块添加到 (defn [x] {:pre [] :post []}...) 就好了,但我不太明白关于能够提供条件的评论-map 作为 arglist 的元数据。
我对 Clojure 很陌生,刚刚开始学习元数据。有人可以举例说明如何做到这一点吗?
谢谢,
马特。
最佳答案
(defn foo ^{:pre [(even? x)] :post [(pos? %)]} [x]
;; <-- metadata attached to arglist --> \ /
;; |
;; arglist -----/
(inc x))
调用上面的 REPL:
user=> (foo 0)
1
user=> (foo -2)
AssertionError Assert failed: (pos? %) user/foo (NO_SOURCE_FILE:2)
user=> (foo 1)
AssertionError Assert failed: (even? x) user/foo (NO_SOURCE_FILE:2)
关于Clojure 条件映射参数作为 arglist 的元数据提供,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28192674/