clojure.spec:`alt` vs`or`用于序列规范 [英] clojure.spec: `alt` vs `or` for sequence spec

查看:105
本文介绍了clojure.spec:`alt` vs`or`用于序列规范的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关注clojure.spec的指南( http://clojure.org/guides/spec ) )。对于序列规范 alt 之间的区别,我感到困惑。

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 用于连接嵌套的regex规范,其中使用 / or 指定子序列。在你的例子中它没有什么区别,因为你没有使用嵌套的regex规范。下面是一个例子:

s/alt is for concatenating nested regex specs where using s/or specifies a subsequence. 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

如您所见,其中开始新的正则表达式上下文的子序列,而 alt 指定相反的:

As you can see, or specifies a sub-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` vs`or`用于序列规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆