如何选择最小的完整定义 Ord?
How was the minimal complete definition Ord chosen?
Data.Ord
包括这些方法:
compare :: a -> a -> Ordering
(<) :: a -> a -> Bool
(<=) :: a -> a -> Bool
(>) :: a -> a -> Bool
(>=) :: a -> a -> Bool
max :: a -> a -> a
min :: a -> a -> a
最小的完整定义是compare | (<=)
。
我了解如何从这两种方法中的任何一种确定其他方法。
我不明白为什么 (>)
(例如)也不能用作最小的完整定义。 not (a > b)
等同于 a <= b
.
将 (>)
作为最小完整定义排除在外的决定是武断的,还是我遗漏了什么?
我认为 the source 对此有所启发:
class (Eq a) => Ord a where
compare :: a -> a -> Ordering
(<), (<=), (>), (>=) :: a -> a -> Bool
max, min :: a -> a -> a
compare x y = if x == y then EQ
else if x <= y then LT
else GT
x < y = case compare x y of { LT -> True; _ -> False }
x <= y = case compare x y of { GT -> False; _ -> True }
x > y = case compare x y of { GT -> True; _ -> False }
x >= y = case compare x y of { LT -> False; _ -> True }
如您所见,所有比较都是根据 compare
实现的,比较本身是根据 <=
实现的。这个选择有点随意(尽管正如 Willem van Onsem 所写,它可能源于数学传统),但这确实排除了允许使用附加运算符作为最小定义的可能性。 compare
.
只能有一个默认定义
Data.Ord
包括这些方法:
compare :: a -> a -> Ordering
(<) :: a -> a -> Bool
(<=) :: a -> a -> Bool
(>) :: a -> a -> Bool
(>=) :: a -> a -> Bool
max :: a -> a -> a
min :: a -> a -> a
最小的完整定义是compare | (<=)
。
我了解如何从这两种方法中的任何一种确定其他方法。
我不明白为什么 (>)
(例如)也不能用作最小的完整定义。 not (a > b)
等同于 a <= b
.
将 (>)
作为最小完整定义排除在外的决定是武断的,还是我遗漏了什么?
我认为 the source 对此有所启发:
class (Eq a) => Ord a where
compare :: a -> a -> Ordering
(<), (<=), (>), (>=) :: a -> a -> Bool
max, min :: a -> a -> a
compare x y = if x == y then EQ
else if x <= y then LT
else GT
x < y = case compare x y of { LT -> True; _ -> False }
x <= y = case compare x y of { GT -> False; _ -> True }
x > y = case compare x y of { GT -> True; _ -> False }
x >= y = case compare x y of { LT -> False; _ -> True }
如您所见,所有比较都是根据 compare
实现的,比较本身是根据 <=
实现的。这个选择有点随意(尽管正如 Willem van Onsem 所写,它可能源于数学传统),但这确实排除了允许使用附加运算符作为最小定义的可能性。 compare
.