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.