Clojure Spec匹配并生成可变长度的有序向量

时间:2017-04-05 11:58:47

标签: clojure clojure.spec

让我们从

的常规序列开始
(require '[clojure.spec     :as spec]
         '[clojure.spec.gen :as gen])
(spec/def ::cat (spec/cat :sym symbol? :str string? :kws (spec/* keyword?)))

匹配矢量

(spec/conform ::cat '[af "5"])
=> {:sym af, :str "5"}
(spec/conform ::cat '[af "5" :key])
=> {:sym af, :str "5", :kws [:key]}

还列出了

(spec/conform ::cat '(af "5"))
=> {:sym af, :str "5"}
(spec/conform ::cat '(af "5" :key))
=> {:sym af, :str "5", :kws [:key]}

如果我们想要限制这一点,我们可以尝试使用spec/tuple;但遗憾的是它只匹配固定长度向量,即它至少需要一个空列表作为元组的最后一部分:

(spec/def ::tuple (spec/tuple symbol? string? (spec/* keyword?)))
(spec/conform ::tuple '[af "5"])
=> :clojure.spec/invalid
(spec/exercise ::tuple)
=> ([[r "" ()] [r "" []]] [[kE "" (:M)] [kE "" [:M]]] ...)

我们还可以尝试使用::cat向<{1}}添加其他条件:

spec/and

匹配精细

(spec/def ::and-cat
  (spec/and vector? (spec/cat :sym symbol? :str string? :kws (spec/* keyword?))))

但遗憾的是无法生成它自己的数据,因为(spec/conform ::and-cat '[af "5"]) => {:sym af, :str "5"} (spec/conform ::and-cat '[af "5" :key]) => {:sym af, :str "5", :kws [:key]} (spec/conform ::and-cat '(af "5" :key)) => :clojure.spec/invalid 的生成器只生成列表,这些列表当然不符合spec/cat谓词:

vector?

总结一下:如何编写一个能够接受和生成(spec/exercise ::and-cat) => Couldn't satisfy such-that predicate after 100 tries. [hi "there"]等向量的规范?

还可以将问题重新解释为&#34;是否有[my "dear" :friend]替代生成向量而不是列表?&#34;或&#34;是否可以将{kind}参数传递给spec/cat?&#34;或者&#34;我可以将生成器附加到一个规范,该规范获取原始生成器的输出并将其转换为向量吗?&#34;。

3 个答案:

答案 0 :(得分:2)

独立于规范创建正则表达式模式:

(require '[clojure.spec :as s] '[clojure.spec.gen :as gen])

(def pattern 
  (s/cat :sym symbol? :str string? :kws (s/* keyword?)))

(s/def ::solution
  (s/with-gen (s/and vector? pattern) 
              #(gen/fmap vec (spec/gen pattern))))

(s/valid? ::solution '(af "5" :key))  ;; false

(s/valid? ::solution ['af "5" :key])  ;; true

(gen/sample (s/gen ::solution) 4)
;; ([m ""] [. "" :Q] [- "" :?-/-9y :_7*/!] [O._7l/.?*+ "z" :**Q.tw.!_/+!gN :wGR/K :n/L])

答案 1 :(得分:0)

(spec/conform ::solution '(N-G.?8?4/- "" :G7y_.?Gx_/Oy1Dv :g!/Ooh0 :N-??h/o+cN)) => {:sym N-G.?8?4/-, :str "", :kws [:G7y_.?Gx_/Oy1Dv :g!/Ooh0 :N-??h/o+cN]} 开始,没有解决这个问题的简单方法。一种可能的解决方案是修改生成器以将cat给出的序列转换为如下的向量:

{{1}}

然后我们可以看到它们产生并接受正确的数据:

{{1}}

虽然它有一个问题,但规范并没有验证输入是一个向量,它接受列表等序列:

{{1}}

答案 2 :(得分:0)

要添加Alex的解决方案,这里有一个定义vector-cat正则表达式操作的宏:

(defmacro vcat
  "Takes key+pred pairs, e.g.

  (vcat :e even? :o odd?)

  Returns a regex op that matches vectors, returning a map containing
  the keys of each pred and the corresponding value. The attached
  generator produces vectors."
  [& key-pred-forms]
  `(spec/with-gen (spec/and vector? (spec/cat ~@key-pred-forms))
     #(gen/fmap vec (spec/gen (spec/cat ~@key-pred-forms)))))