如何取消嵌套序列规范?
How to unnest sequence spec?
使用 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]}]
所以我正在寻找的是一个函数或宏(比如 unnest),它会起作用:
(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]}]
我怎样才能得到它?
您需要继续使用正则表达式:
(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]}}
使用 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]}]
所以我正在寻找的是一个函数或宏(比如 unnest),它会起作用:
(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]}]
我怎样才能得到它?
您需要继续使用正则表达式:
(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]}}