Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
868 views
in Technique[技术] by (71.8m points)

haskell - Why "and []" is True and "or []" is False

Why "and" on an empty list returns true, does it imply that an empty list holds True? Sorry but I cannot read and comprehend this correctly, so please correct me. Thanks.

Prelude> and []
True
Prelude> or []
False
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In mathematics, it's often useful to talk about a binary operation, such as &&, ||, +, *, etc as having an identity. The identity is a value e such that the following property holds for some generic binary operation <>

e <> x = x
x <> e = x

For the operators I listed above, they are commutative, meaning that x <> y = y <> x for all x and y, so we only have to check one of the above properties. For and, the binary operator in question is &&, and for or the binary operator is ||. If we make a Cayley table for these operations, it would look like

&&    | False | True
------+-------+------
False | False | False
True  | False | True


||    | False | True
------+-------+------
False | False | True
True  | True  | True

So as you can see, for && if you have True && False and True && True, the answer is always the second argument to &&. For ||, if you have False || False and False || True, the answer is always the second argument, so the first argument of each must be the identity element under those operators. Put simply:

True && x = x
x && True = x

False || x = x
x || False = x

Thus, the preferred answer when there are no elements to perform the operator on is the identity element for each operation.


It might help to also think about the identity elements for + and *, which are 0 and 1 respectively:

x + 0 = x = 0 + x
x * 1 = x = 1 * x

You can also extend this to operations like list concatenation (++ with []), function composition for functions of type a -> a ((.) with id), along with many others. Since this is starting to look like a pattern, you might ask if this is already a thing in Haskell, and indeed it is. The module Data.Monoid defines the Monoid typeclass that abstracts this pattern, and it's minimal definition is

class Monoid a where
    mempty :: a                   -- The identity
    mappend :: a -> a -> a        -- The binary operator

And it even aliases mappend as <> for ease of use (it was no accident that I choose it above for a generic binary operator). I encourage you to look at that module and play around with its definitions. The source code is quite easy to read and is enlightening.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...