Could Ord
and Enum
be one typeclass? Why doesn't Enum
require Eq
?
Ord. The Ord class is used for totally ordered datatypes. Instances of Ord can be derived for any user-defined datatype whose constituent types are in Ord. The declared order of the constructors in the data declaration determines the ordering in derived Ord instances.
In Haskell, they are represented by the type classes Bounded (for types with minimum and maximum bounds) and Enum (for types whose values can be enumerated by the Int values). The Bounded type class defines only two methods: class Bounded a where minBound :: a maxBound :: a {-# MINIMAL minBound, maxBound #-}
There are things that can be enumerated without an order. For example:
data Color = Red | Green | Blue deriving Enum
Which order should colors have? There is no inherent order, even though the colors can be enuemrated.
There are also things that can be enumerated but not compared for equality. Floats, for example, have a NaN value that isn't equal to anything. Floats can be enumerated, however.
Enum
represents types that can be mapped to/from integers. This doesn't say anything about how those types should be sorted, merely that you can represent them with integers.
Ord
represents ordered types. This is different than types that can be mapped to integers. For example, you can't map arbitrary-precision floating point values to integers, but you can order them. And while you technically could try and map Floats to integers, nobody in their right mind would do so.
As for Eq
, Ord
requires this because it doesn't make sense to have a totally ordered datatype that doesn't support equality. However, Enum
has no need for Eq
. Since Enum
doesn't provide any ordering guarantees, it doesn't provide equality guarantees either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With