Prelude "and" and "or" functions in empty lists

I just started playing with Haskell using GHCI. REPL comes with many built-in functions. For example, and and or to shorten logical lists [Bool] -> Bool . It was pretty surprising to me that for empty lists it gives:

 Prelude> and [] True Prelude> or [] False 

Are there any good reasons for this behavior? I expected the opposite results. Even False in both cases seems more reasonable to me.

+5
source share
2 answers

In both cases, they give a single element of the operation:

 True && x == x False || x == x 

For each operation, this is a boolean that "does nothing", making it the perfect choice to return when you are not receiving anything as input!

This is the same as sum and product starting at 0 and 1 respectively.

+9
source

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

  • all p searches the list to find counterexample for the predicate p . It returns False if and only if such a counterexample is found.
  • any p searches the list to find an example that satisfies the predicate p . It returns True if and only if such an example is found.

Thus:

  • all p [] true because the empty list does not contain a counterexample for p .
  • any p [] is false because the empty list does not contain examples satisfying p .

Note that:

 and == all id or == any id 

So, this argument continues to and, or :: [Bool] -> Bool .

Note that mathematical logic often also works as follows:

 -- "All unicorns are Argentinian." βˆ€x. unicorn(x) β†’ argentinian(x) 

This sentence is true if unicorns do not exist. Logical beginners are also confused by this ...

+7
source

Source: https://habr.com/ru/post/1208382/


All Articles