理解 Haskell 的 Bool 推导 Ord [英] Understanding Haskell's Bool Deriving an Ord

查看:14
本文介绍了理解 Haskell 的 Bool 推导 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 形成 有界点阵*,其中FalsebottomTruetop.这个有界格定义了一个(总)排序,其中 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.)

布尔运算 andor 也可以分别视为 meetjoin,在这个格子.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.

您可以使用 minmax 在 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

请注意,在存在 另一种底部的情况下,这些定义是不等价的,因为 (&&)(||) 是短路的(当第一个参数是 FalseTrue,分别)而 minmax 不是.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆