[Haskell-beginners] safe versions of pred and succ?

Michael Orlitzky michael at orlitzky.com
Sun Jan 15 19:05:26 UTC 2017


On 01/14/2017 02:35 AM, Graham Gill wrote:
> 
> Do I need two different versions of f, one for Bounded a and one for 
> non-Bounded a? Is there a more elegant way to take care of this problem? 
> I don't know much about all of the type magic available in GHC.
> 

You probably want your own typeclass instead of Enum, even if it means
generating a bunch of very boring instances of it for the types you want
"f" to work on.

The fact that "pred" should throw a runtime error on "minBound" is a
documented fact of the Enum typeclass, and you should stay far far away
from such things in your own code. Besides that, there's a weird
interaction between the semantic meaning of Enum and Bounded. For
example, here's a perfectly valid enumeration of boolean values:

  True, False, True, False, ...

In your case it would be fine to have (pred False) == True, but instead
you get a runtime error thanks to the Bounded instance. So being Bounded
rules out some otherwise valid (and fine for your purposes) Enum instances.

Your "f" should also work on a singleton type:

  ghci> data Foo = Foo deriving (Eq,Show)
  ghci> instance Enum Foo where toEnum _ = Foo; fromEnum _ = 0;
  ghci> groupConsecutive [Foo,Foo,Foo,Foo]
  [[Foo,Foo,Foo,Foo]]

But any Bounded instance for Foo would mess that up. Basically, the
pre-existing Enum instances aren't exactly what you want.



More information about the Beginners mailing list