clojure.spec:`alt` 与 `or` 序列规范 [英] clojure.spec: `alt` vs `or` for sequence spec
问题描述
我正在关注 clojure.spec 的指南 (http://clojure.org/guides/spec).我对序列规范的 alt
和 or
之间的区别感到困惑.
I'm following clojure.spec's guide (http://clojure.org/guides/spec). I'm confused by the difference between alt
and or
for sequence spec.
对我而言,以下两个示例同样有效.那么两者有什么区别呢?
For me the two following examples work equally well. So what's the difference between the two?
; Use `alt`
(s/def ::config (s/* (s/cat :prop string?
:val (s/alt :s string? :b boolean?))))
(s/explain ::config ["-server" "foo" "-verbose" true "-user" 13])
; Use `or`
(s/def ::config (s/* (s/cat :prop string?
:val (s/or :s string? :b boolean?))))
(s/explain ::config ["-server" "foo" "-verbose" true "-user" 13])
推荐答案
s/alt
用于连接嵌套的正则表达式规范,其中使用 s/or
指定嵌套序列.在您的示例中,它没有任何区别,因为您没有使用嵌套的正则表达式规范.下面是一个例子:
s/alt
is for concatenating nested regex specs where using s/or
specifies a nested sequence. In your example it doesn't make a difference since you are not using nested regex specs. Here is an example:
(s/def ::number-regex (s/* number?))
(s/def ::or-example (s/cat :nums (s/or :numbers ::number-regex)))
(s/valid? ::or-example [1 2 3])
;;-> false
(s/valid? ::or-example [[1 2 3]])
;;-> true
如您所见,or
指定了一个嵌套序列,其中开始了新的正则表达式上下文,而 alt
指定了相反的内容:
As you can see, or
specifies a nested sequence in which a new regex context is started, whereas alt
specifies the opposite:
(s/def ::alt-example (s/cat :nums (s/alt :numbers ::number-regex)))
(s/valid? ::alt-example [1 2 3])
;;-> true
(s/valid? ::alt-example [[1 2 3]])
;;-> false
这篇关于clojure.spec:`alt` 与 `or` 序列规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!