Question: Why every? function returns true with empty vector in Clojure?

Question

Why every? function returns true with empty vector in Clojure?

Answers 1
Added at 2016-12-31 01:12
Tags
Question

I came across this weird behaviour:

(every? true? [])
=> true

(every? false? [])
=> true

(every? odd? [])
=> true

And list goes like that...

It should return false instead of true I guess.

What is the reason of this function designed that way?

Answers
nr: #1 dodano: 2016-12-31 01:12

The general rule in most languages that have functions like every? and not-any? is that they return the identity value when given an empty array. This ensures that you get the same result when you combine operations on subsets of the array. The rule is that

(and (every? true? array1) (every? true? array2))

should return the same thing as

(every? true? (concat array1 array2))

If every? returned false for an empty array, this would break the equivalence when either of the two arrays is empty.

Similarly, not-any? returns false for an empty array to ensure that

(not-any? true? (concat array1 array2))

is the same as

(or (not-any? true? array1) (not-any? true? array2))
Source Show
◀ Wstecz