使用Clojure core.spec我可以拥有以下内容:
(s/conform (s/cat :a even? :b (s/* odd?) :a2 even? :b2 (s/* odd?)) [2 3 5 12 13 15])
=> {:a 2, :b [3 5], :a2 12, :b2 [13 15]}
我想要的是通过外部化子规范来删除冗余:
(s/def ::even-followed-by-odds
(s/cat :a even? :b (s/* odd?)))
但
(s/conform (s/tuple ::even-followed-by-odds ::even-followed-by-odds) [2 3 5 12 13 15])
=> :clojure.spec/invalid
这个有效:
(s/conform (s/tuple ::even-followed-by-odds ::even-followed-by-odds) [[2 3 5] [12 13 15]])
=> [{:a 2, :b [3 5]} {:a 12, :b [13 15]}]
所以我正在寻找的是一个函数或宏(比如说不需要),它会起作用:
(s/conform (s/tuple (unnest ::even-followed-by-odds) (unnest ::even-followed-by-odds)) [2 3 5 12 13 15])
=> [{:a 2, :b [3 5]} {:a 12, :b [13 15]}]
我怎么能得到它?
答案 0 :(得分:3)
你需要留在正则表达式:
(s/conform (s/cat :x ::even-followed-by-odds :y ::even-followed-by-odds) [2 3 5 12 13 15])
{:x {:a 2, :b [3 5]}, :y {:a 12, :b [13 15]}}