作为 arglist 的元数据提供的 Clojure 条件映射参数
Clojure condition-map parameter provided as metadata of the arglist
在特殊形式的 Clojure 文档中 (http://clojure.org/special_forms)
condition-map参数说明如下:
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 []}...) 就好了,但我不太明白关于能够提供条件映射作为 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 文档中 (http://clojure.org/special_forms)
condition-map参数说明如下:
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 []}...) 就好了,但我不太明白关于能够提供条件映射作为 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)