2

假设我们有一个宏,它接受一个必需的参数,后跟可选的位置参数,例如

(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可以很好地锻炼它的方式来指定一个带有命名参数的宏?

附录:

keys*用 an包裹and似乎exercise-fn再次中断,即使它有一个必需的命名 arg。

4

1 回答 1

1

你不能使用exercise-fn宏,因为你不能使用apply宏。(请注意,它被称为练习fn :)。

这与 完全一样(apply dress ["foo"]),产生了熟悉的“不能获取宏的值”。您看到的不同错误消息是因为它适用于 var 而不是宏,因为实际发生的情况就像(apply #'user/dress ["foo"]).

于 2017-04-21T15:12:23.960 回答