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

Rov*_*ion 5 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?)))
Run Code Online (Sandbox Code Playgroud)

匹配向量

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

还有名单

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

如果我们想限制这一点,我们可以尝试使用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]]] ...)
Run Code Online (Sandbox Code Playgroud)

我们还可以尝试在::catwith上添加一个额外的条件spec/and

(spec/def ::and-cat
  (spec/and vector? (spec/cat :sym symbol? :str string? :kws (spec/* keyword?))))
Run Code Online (Sandbox Code Playgroud)

匹配得很好

(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
Run Code Online (Sandbox Code Playgroud)

但遗憾的是无法生成自己的数据,因为生成器 forspec/cat只生成当然不符合vector?谓词的列表:

(spec/exercise ::and-cat)
=> Couldn't satisfy such-that predicate after 100 tries.
Run Code Online (Sandbox Code Playgroud)

所以总结一下:如何编写一个既能够接受又能够生成向量的规范[hi "there"] [my "dear" :friend]

人们还可以将这个问题重新表述为“是否有替代方法可以spec/cat生成向量而不是列表?” 或“是否可以将 :kind 参数传递给spec/cat?” 或“我可以将生成器附加到规范中,该规范获取原始生成器的输出并将其转换为向量?”。

Ale*_*ler 3

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

(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])
Run Code Online (Sandbox Code Playgroud)