I've just started to play with Haskell using GHCI. The REPL comes with a bunch of built in functions. For example and
and or
to reduce boolean lists [Bool] -> Bool
. It was quite suprising to me that for empty lists it gives:
Prelude> and []
True
Prelude> or []
False
Are there any good reasons for such a behaviour? I was kinda expecting the opposite results. Even False
in both cases looks more reasonable to me.
In both cases, they give the identity element of the operation:
True && x == x
False || x == x
For each operation, it's the boolean that "does nothing", which makes it the perfect choice to return when you get nothing as an input!
This is the same way that sum
and product
start off with 0
and 1
respectively.
This is easier to understand if we talk instead about all, any :: (a -> Bool) -> [a] -> Bool
. Intuitively:
all p
searches a list to find a counterexample to the predicate p
. It returns False
if and only if such a counterexample is found.any p
searches a list to find an example that satisfies the predicate p
. It returns True
if and only if such an example is found.Therefore:
all p []
is true because the empty list does not contain any counterexamples to p
.any p []
is false because the empty list does not contain any examples that satisfy p
.Note that:
and == all id
or == any id
So this reasoning extends to and, or :: [Bool] -> Bool
.
Note that mathematical logic often also works like this:
-- "All unicorns are Argentinian."
∀x. unicorn(x) → argentinian(x)
This proposition is true if unicorns don't exist. Logic newbies get confused by this as well...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With