Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prelude "and" and "or" functions on empty lists [duplicate]

Tags:

haskell

ghci

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.

like image 265
Yury Tarabanko Avatar asked Dec 04 '14 20:12

Yury Tarabanko


2 Answers

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.

like image 67
Tikhon Jelvis Avatar answered Nov 09 '22 22:11

Tikhon Jelvis


This is easier to understand if we talk instead about all, any :: (a -> Bool) -> [a] -> Bool. Intuitively:

  1. 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.
  2. 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:

  1. all p [] is true because the empty list does not contain any counterexamples to p.
  2. 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...

like image 41
Luis Casillas Avatar answered Nov 10 '22 00:11

Luis Casillas