Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Ord and Enum sometimes incompatible in Haskell?

Could Ord and Enum be one typeclass? Why doesn't Enum require Eq?

like image 235
L01man Avatar asked Jul 15 '12 21:07

L01man


People also ask

What does ORD do in Haskell?

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.

What is enum Haskell?

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 #-}


2 Answers

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.

like image 122
dflemstr Avatar answered Sep 28 '22 00:09

dflemstr


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.

like image 23
Lily Ballard Avatar answered Sep 28 '22 01:09

Lily Ballard