F. *_*Zer 0 haskell functional-programming
Ord这是数据类型实例的最小完整定义吗Maybe?这是对的吗 ?
instance Ord (Maybe a) where
compare (Just x) (Just y) | x < y = LT
| x > y = GT
| otherwise = EQ
compare _ _ = LT
Run Code Online (Sandbox Code Playgroud)
instance Ord (Maybe a) where
(Just x) <= (Just y) = x <= y
_ _ = False
Run Code Online (Sandbox Code Playgroud)
从涵盖所有可能的模式情况的意义上来说,它是否完整?当然; 两个定义的末尾都有一个包罗万象的内容。然而,这不是一个很好的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
Run Code Online (Sandbox Code Playgroud)
<=或者,写成
instance Ord a => Ord (Maybe a) where
Nothing <= _ = True
Just _ <= Nothing = False
Just x <= Just y = x <= y
Run Code Online (Sandbox Code Playgroud)