首页 > 解决方案 > 为 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

标签: haskellfunctional-programming

解决方案


它是否完整,它涵盖了所有可能的模式案例?当然; 您在两个定义的末尾都有一个包罗万象的内容。但是,这不是一个很好的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实例,加上我们称为的额外值,因此它简单地定义为排序的最小值。现有关系等价于以下MaybeMaybe aaNothingNothing

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

推荐阅读