Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a Haskell type "deriving Integral" need to be "deriving Enum"?

Tags:

haskell

I've recently been trying to "learn me a Haskell," and I'd like to create a new type to represent an integer state, without just using a raw Integer (for type safety and code clarity). Specifically, the following code compiles:

newtype AuxState = AuxState Integer
  deriving (Eq, Ord, Num, Integral, Real, Enum)

However, since there are an infinite number of states in my application, I have no interest in converting this state into an Enum. However, if I try to remove the deriving (Enum) statement so it's just deriving (Eq, Ord, Num, Integral, Real), the compiler complains:

No instance for (Enum AuxState)
  arising from the 'deriving' clause of a data type declaration
Possible fix:
  add an instance declaration for (Enum AuxState)
  or use a standalone 'deriving instance' declaration,
       so you can specify the instance context yourself
When deriving the instance for (Integral AuxState)

I find it hard to believe that Haskell forces a type in the Integral class to also be in the Enum class; shouldn't it just be the other way around? Is there a reason for this, or am I doing/understanding something wrong?

like image 664
btown Avatar asked Apr 11 '12 04:04

btown


2 Answers

All Integral are necessarily Enum because the foundations of Integral math are the succ and pred operations. (Technically Enum is standing in for a proper type hierarchy where an Integral type is a mathematical semigroup, I think.) The other way around seems even more wrong: you mean that every Enum should be Integral? Does this include random ADTs like

data Foo = A | B | C | D | E | F | G deriving (Enum)

?

(Every Enum should be isomorphic to a subset of Integral, surely, but that actually suggests it going the other direction: Integral can represent any Enum but not vice versa, so Integral is kind of the ur-Enum.)

like image 137
geekosaur Avatar answered Sep 21 '22 23:09

geekosaur


The technical reason is because is because Integral is defined in Prelude as follows:

class (Real a, Enum a) => Integral a where
   ...

The mathematical reason is that every integral type is enumerable but not vice versa. Think about rational numbers for example. Note, that Enum does not imply finite enumeration as is shown by Integer.

like image 44
jmg Avatar answered Sep 20 '22 23:09

jmg