haskell - 为 Maybe 数据类型定义 Ord 实例
问题描述
这是数据类型Ord
实例的最小完整定义吗?Maybe
这是对的吗 ?
instance Ord (Maybe a) where
compare (Just x) (Just y) | x < y = LT
| x > y = GT
| otherwise = EQ
compare _ _ = LT
instance Ord (Maybe a) where
(Just x) <= (Just y) = x <= y
_ _ = False
解决方案
它是否完整,它涵盖了所有可能的模式案例?当然; 您在两个定义的末尾都有一个包罗万象的内容。但是,这不是一个很好的Ord
例子,因为它违反了文档中规定的约束。
传递性
如果 x <= y && y <= z = True,则 x <= z = True
反身性
x <= x = 真
反对称
如果 x <= y && y <= x = True,则 x == y = True
特别是,您提出的第二个关系不是自反的,因为Nothing <= Nothing
它是错误的。您的第一个关系将表现得更加奇怪,因为Nothing <= Nothing
将返回 true 但Nothing >= Nothing
将返回 false。
与 同构的观察的内置Ord
实例,加上我们称为的额外值,因此它简单地定义为排序的最小值。现有关系等价于以下Maybe
Maybe a
a
Nothing
Nothing
instance Ord a => Ord (Maybe a) where
compare Nothing Nothing = EQ
compare Nothing (Just _) = LT
compare (Just _) Nothing = GT
compare (Just x) (Just y) = compare x y
或者,写成<=
,
instance Ord a => Ord (Maybe a) where
Nothing <= _ = True
Just _ <= Nothing = False
Just x <= Just y = x <= y
推荐阅读
- python - sklearn 中用于 10cv SVM 回归的分类(字符串)特征
- php - PHP 标头在 WordPress ajax 调用中不起作用
- mysql - 加入 3 个表并选择计数
- excel - 将多列数据拆分为行
- selenium - 如何在appium中上传文件以实现移动应用自动化?
- reporting-services - 需要将 Microstrategy 报告转换为 SSRS 平台的最佳实践或工具
- mongodb - mongodb $facet 未接受的结果
- python - 如何在 Pandas 中去除字符串列开头和结尾的标点符号
- mysql - Ejabberd Disco Itam 不来
- java - 如何调用基类中存在的参数化构造函数?