Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `&` and `and` in Clojure Spec?

I seem to have a hard time keeping apart the meaning of the & and and operators of Clojure Spec. They both seem to do sort of the same thing, only one is noted as a regex operator, a difference I'm not sure I understand the importance of.

like image 411
Rovanion Avatar asked Mar 31 '17 07:03

Rovanion


1 Answers

We can see the difference between the two if we sample some data from them:

(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)

As we can see spec/and matches single occurrences of what matches the two predicates #{:a :c} and #{: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/& on the other hand matches what's accepted by the predicates as part of a sequence.

like image 178
Rovanion Avatar answered Nov 04 '22 09:11

Rovanion