【发布时间】:2017-04-11 07:36:13
【问题描述】:
假设我们有一个宏,它接受一个必需的参数,后跟可选的位置参数,例如
(require '[clojure.spec :as spec]
'[clojure.spec.gen :as gen])
(defmacro dress [what & clothes]
`(clojure.string/join " " '(~what ~@clothes)))
(dress "me")
=> "me"
(dress "me" :hat "favourite")
=> "me :hat favourite"
我们为它写一个规范
(spec/def ::hat string?)
(spec/fdef dress
:args (spec/cat :what string?
:clothes (spec/keys* :opt-un [::hat]))
:ret string?)
我们会发现spec/exercise-fn 无法执行宏
(spec/exercise-fn `dress)
;1. Unhandled clojure.lang.ArityException
; Wrong number of args (1) passed to: project/dress
即使函数生成器生成的数据被宏很好地接受:
(def args (gen/generate (spec/gen (spec/cat :what string?
:clothes (spec/keys* :opt-un [::hat])))))
; args => ("mO792pj0x")
(eval `(dress ~@args))
=> "mO792pj0x"
(dress "mO792pj0x")
=> "mO792pj0x"
另一方面,定义一个函数并以相同的方式执行它可以正常工作:
(defn dress [what & clothes]
(clojure.string/join " " (conj clothes what)))
(spec/def ::hat string?)
(spec/fdef dress
:args (spec/cat :what string?
:clothes (spec/keys* :opt-un [::hat]))
:ret string?)
(dress "me")
=> "me"
(dress "me" :hat "favourite")
=> "me :hat favourite"
(spec/exercise-fn `dress)
=> ([("") ""] [("l" :hat "z") "l :hat z"] [("") ""] [("h") "h"] [("" :hat "") " :hat "] [("m") "m"] [("8ja" :hat "N5M754") "8ja :hat N5M754"] [("2vsH8" :hat "Z") "2vsH8 :hat Z"] [("" :hat "TL") " :hat TL"] [("q4gSi1") "q4gSi1"])
如果我们看一下具有相似定义模式的内置宏,我们会看到同样的问题:
(spec/exercise-fn `let)
; 1. Unhandled clojure.lang.ArityException
; Wrong number of args (1) passed to: core/let
一件有趣的事情是exercise-fn 在总是存在一个必需的命名参数时可以正常工作:
(defmacro dress [what & clothes]
`(clojure.string/join " " '(~what ~@clothes)))
(spec/def ::hat string?)
(spec/def ::tie string?)
(spec/fdef dress
:args (spec/cat :what string?
:clothes (spec/keys* :opt-un [::hat] :req-un [::tie]))
:ret string?)
(dress "me" :tie "blue" :hat "favourite")
=> "me :tie blue :hat favourite"
(spec/exercise-fn `dress)
换句话说:似乎有一些隐藏的参数在正常调用期间总是传递给宏,而这些参数没有被规范传递。遗憾的是,我对 Clojure 的经验还不够了解这些细节,但一只小鸟告诉我,有些东西名为 &env 和 &form。
但我的问题归结为:是否可以使用命名参数指定宏,以使spec/exercise-fn 可以很好地锻炼它?
附录:
用and 包裹keys* 似乎再次破坏exercise-fn,即使它有一个必需的命名arg。
【问题讨论】:
标签: clojure clojure.spec