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

Graham Gill math.simplex at gmail.com
Mon Jan 16 15:59:38 UTC 2017


Thanks very much for that clear reply Michael.

I don't have an application in mind specifically, the example function 
groupConsecutive just came up in another message and set me wondering: 
if I have a function to work on types of class A, but types that are 
instances of both class A and class B are problematic, is there a way to 
distinguish the cases? As you say, it's probably not class A that I want 
my function to work over, but instead my own type class.

Graham

On 15 Jan 2017 14:09, "Michael Orlitzky" <michael at orlitzky.com 
<mailto:michael at orlitzky.com>> wrote:

    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.

    _______________________________________________
    Beginners mailing list
    Beginners at haskell.org <mailto:Beginners at haskell.org>
    http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
    <http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20170116/e3ffa1c9/attachment.html>


More information about the Beginners mailing list