Enum class
Jan-Willem Maessen
jmaessen@mit.edu
Wed, 24 Oct 2001 16:11:12 -0400
"Simon Peyton-Jones" <simonpj@microsoft.com> responds to me (and
others):
> The Report Section 6.3.4 (about Enum) refers back to Section 3.10 for
> semantics for enumFrom etc. There you'll find a specification for
> what they mean, including Float and Double. If I can improve the
> wording
> I'd be glad to do so, but it does look defined to me.
I found it after a bit of hunting, and still managed to be
confused---probably more by the layers of indirection, though. I
think the proposed consolidation of 3.10 into 6.3.4 will prove
helpful.
Both of my proposals:
> | * In the report, give clear and explicit definitions of
> | enumFrom... for Float and Double. This could be done right now.
> | * Definitions of enumFrom... for Int which deal gracefully with
> | overflow might be a nice addition to the report as people get them
> | wrong.
Seem to fall under this response:
> Hmm. If the specification is ok, I'm disinclined to add an
> implementation
> too -- there's every chance I'll get it wrong too!
Which I can fully understand given the ensuing discussion by Malcolm
Wallace et. al. about the given code for pred and succ!
Nonetheless, I've implemented enumeration subtly wrong in too many
different ways myself (and I'm not the only one). In an effort to
remedy this (and because I opened my mouth and said "there ought to be
an implementation"!), I've thrown together a "how to do it" library:
http://www.csg.lcs.mit.edu/~earwig/Enum.lhs
It features as many Enum functions as possible for types in the
following classes:
* Bounded Integral (Int, Word, etc.) --- does the right thing with
bounds, avoids negative values so Word ought to work, etc.
* Bounded. Must fit inside an Int, toEnum and fromEnum must be
defined.
* Floating. Does appropriately peculiar things with upper bounds of
enumerations.
* Num. Assumes an unbounded type. This is the weakest point:
- We must give a different fromEnum for Integer and RealFrac
- We must assume that we *either* have a total ordering Ord or
negative numbers for enumFromThen.
- Bounded enumeration requires either Ord or some very clever
type-specific function. For example, consider defining
Enum (Complex a).
The code is tested for various fencepost errors, but may still have
missed details of the spec even after multiple re-readings. Feel free
to send me comments.
-Jan-Willem Maessen
Eager Haskell Project
jmaessen@mit.edu