Ranges and the Enum class

Aaron Denney wnoise at ofb.net
Sat Mar 18 01:05:52 EST 2006

On 2006-03-17, Ross Paterson wrote:
> Speaking of confusing, try
> 	[0, 0.3 .. 2]::[Rational]

Right.  I had forgotten that -- Rational is exact, yet has the weird
"closest endpoint" behavior of Float and Double.

> Also, toEnum and fromEnum would make more sense mapping from and to
> Integer.  It seems that succ and pred are unused.

So, I think I'll put together a proposal, well two.
Okay, three.

First, change toEnum and fromEnum to Integer.

Then there is a choice between:
(1): Remove Double, Float, and Rational from Enum.  They're no longer
usable in arithmetic sequences.

Pro: Very easy to do.
     Sequences can still be constructed by starting with
         integers, and scaling to convert.
Con: Loses some functionality (though it's questionable
         functionality given rounding).

(2): Split Enum into the classes Enum and ArithmeticSequence
and change what the various [..] desugars to.

class Enum a where
    succ, pred     :: a -> a
    toEnum         :: Integer -> a
    fromEnum       :: a -> Integer

I believe succ and pred aren't used directly by anything else, but I do like
having them.

instance Integer, Int

Rational _could_ be added here by the diagonal representation, but
probably sohuldn't.

class ArithmeticSequence a where
    stepFrom      :: a -> [a]            -- [n..]
    stepFromBy    :: a -> a -> [a]       -- [n,n'..]
    stepFromTo    :: a -> a -> [a]       -- [n..m]
    stepFromByTo  :: a -> a -> a -> [a]  -- [n,n'..m]

instance Int, Integer, Float, Double, Rational.

(a) Make all of them have the "closest endpoint" behavior.
(b) Make all of them have strict "no more than" behavior.

Pros: Clearly divides two seperate uses, while keeping functionality.
      Can re-introduce relationship between Ix and Enum?
Cons: Yet another typeclass.
      Slightly misleading name, as non-arithmetic structures _should_ be
          supported.  Also a bit long.
      But doing so automatically is tricky, as toEnum and fromEnum are no
          longer accessible
      Keeps questionable functionality of non-exact arithmetic sequences.

Personally, I'm for 2(a), but I think even (1) is an improvement.

It's a pity we can't make Enum a subclass of ArithmeticSequence that
provides the methods of its superclass.  Would it be possible to have
"data ... (deriving ArithmeticSequence)" check if (Num a, Ord a) is
defined and use (+), else if Enum a is defined, use fromEnum/toEnum to
go through Integer, else fail.

Where I suppose defined must mean "defined in this module".  Hmm.  That's
kind of ugly.  I can see why these were combined, but it's still really

Steppable might be a better name.

Comments anyone?

Aaron Denney

More information about the Haskell-prime mailing list