理解 Haskell 的 Bool 推导 Ord [英] Understanding Haskell's Bool Deriving an Ord
问题描述
Learn You a Haskell 展示了 Bool
类型:
数据布尔 = 假 |真求导(Ord)
我不明白比较 Bool
的原因.
I don't understand the reason for comparing Bool
's.
> False `compare` True
LT
> True `compare` False
GT
如果 Bool
不是从 Ord
派生的会丢失什么?
What would be lost if Bool
did not derive from Ord
?
推荐答案
Bool
形成 有界点阵*,其中False
是bottom,True
是top.这个有界格定义了一个(总)排序,其中 False
确实严格小于 True
.(它们也是这个格子的唯一元素.)
Bool
forms a bounded lattice* where False
is bottom and True
is top. This bounded lattice defines a (total) ordering where False
really is strictly less than True
. (They are also the only elements of this lattice.)
布尔运算 and
和 or
也可以分别视为 meet 和 join,在这个格子.Meet 找到最大的下界,而 join 找到最小的上界.这意味着 a &&False = False
与说底部的下限和其他任何东西都是底部是一样的,并且 a ||True = True
与说 top 的上限和任何东西都是 top 是一样的.所以 meet 和 join 使用了布尔值的排序属性,相当于你熟悉的布尔运算.
The boolean operations and
and or
can also be looked at as meet and join, respectively, in this lattice. Meet finds the greatest lower bound and join finds the least upper bound. This means that a && False = False
is the same thing as saying that the lower bound of bottom and anything else is bottom, and a || True = True
is the same thing as saying that the upper bound of top and anything is top. So meet and join, which use the ordering property of the booleans, are equivalent to the boolean operations you are familiar with.
您可以使用 min
和 max
在 Haskell 中显示:
You can use min
and max
to show this in Haskell:
False `min` True = False -- this is the greatest lower bound
False && True = False -- so is this
False `max` True = True -- this is the least upper bound
False || True = True -- so is this
这表明您可以从派生的 Ord
实例中定义 &&
和 ||
只是:
This shows that you can define &&
and ||
just from the derived Ord
instance:
(&&) = min
(||) = max
请注意,在存在 另一种底部的情况下,这些定义是不等价的,因为 (&&)
和 (||)
是短路的(当第一个参数是 False
或 True
,分别)而 min
和 max
不是.
Note that these definitions are not equivalent in the presence of a different kind of bottom because (&&)
and (||)
are short-circuiting (non-strict in the second argument when the first is False
or True
, respectively) while min
and max
are not.
另外,一个小的修正:deriving
子句没有说Bool
派生自"Ord
.它指示 GHC 派生类型类 Ord
for 类型 Bool
的实例.
Also, a small correction: The deriving
clause does not say thatBool
"derives from" Ord
. It instructs GHC to derive an instance of the typeclass Ord
for the type Bool
.
* 更具体地说,一个互补分布格.更具体地说,布尔代数.
* More specifically, a complemented distributive lattice. More specifically still, a boolean algebra.
这篇关于理解 Haskell 的 Bool 推导 Ord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!