I'm wondering about the rationale for `Iterable.al...
# getting-started
l
I'm wondering about the rationale for
Iterable.all
returning
true
when called on an empty List:
Copy code
val list = emptyList<Boolean>()
list.all { it } // true
list.none { it } // true
list.any {it } // false
k
Another way of thinking about it is that "all items are X" is equivalent to "there is no item that is not X".
l
Yes, but this definition then wouldn't apply to
none
in the same way 😉
v
Counter-question, why should it not return
true
? All elements in the list are satisfying the predicate.
l
none
and
any
with lambda argument are consistent with the no-argument versions:
Copy code
list.none() == true
list.any() == false
because they check if the list is empty/not empty.
I think the question is quite philosophical in the end "if there are no elements, can we say that they satisfy the predicate?" We can say for sure "There are no elements that don't satisfy the predicate"
But you couldn't apply the same logical negation to the current behavior of
fun <T> none(predicate: T -> Boolean)
l
None seems to answer ‘there are no elements that do satisfy the predicate’
k
None is always the opposite of any.
l
Exactly
True, it's actually not the opposite of
all
.
Good point
v
It's not really a philosophical question. All elements in the list satisfy the predicate. That there is no actual element that could unsatisfy is not relevant. All elements that are in the list satisfy the predicate.
☝️ 1
k
Also, if you wanted
all
to return false for empty lists, whatever programming language you use, you would have to have special treatment for empty lists. The logical way is to return true, because you iterate the list and return false if you find an element that doesn't satisfy the predicate; if you reach the end of the iteration, you return true. This is the case in most languages, not just Kotlin.
l
Yes, this makes the most sense I guess.
Using
all
rather to check if there is at least one element that doesn't fulfill the predicate.
And not to check "do I have any elements and do they all fulfill the predicate"
s
Sometimes I wonder if they should just leave a link to this wiki article in the
.all()
docstring https://en.wikipedia.org/wiki/Vacuous_truth
👏 2
j
Thanks Shawn, I was literally writing that this has little to do with programming, but it's just how logic/math defines this stuff
👍 1
l
Thanks for the article! That gives a good context for this decision.
e
Copy code
(list + x).any() == list.any() || x
(list + x).all() == list.all() && x
(list + x).none() == list.none() && !x
these identities work for lists of all sizes; if you set
list = emptyList()
and try different values of
x
, it is clear there is only one reasonable value for those functions on an empty list
4