Clojure Spec中`&`和`and`的区别是什么?

5

我似乎很难区分 Clojure Spec 的 &and 运算符的含义。它们似乎都做着类似的事情,只是其中一个被标注为正则表达式运算符,这个区别我不确定其重要性。

1个回答

6

如果我们从它们中采样一些数据,就能看到它们之间的差异:

(ns playground
  (:require [clojure.spec     :as spec]
            [clojure.spec.gen :as gen]))

(gen/generate (spec/gen (spec/and #{:a :c} #{:b :a :c})))
=> :a
(gen/sample (spec/gen (spec/and #{:a :c} #{:b :a :c})))
=> (:c :a :c :a :a :a :a :a :a :c)

正如我们所看到的,spec/and匹配符合两个谓词#{:a :c}#{:b :a :c}的单个出现。
(gen/generate (spec/gen (spec/& #{:a :c} #{:b :a :c})))
=> [:c]
(gen/sample (spec/gen (spec/& #{:a :c} #{:b :a :c})))
=> ([:c] [:a] [:a] [:c] [:c] [:c] [:c] [:a] [:c] [:c])

spec/& 另一方面,与谓词作为序列的一部分匹配。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接