“If typeclass a, then a is also an instance of b by this definition.”

Saurabh Nanda saurabhnanda at gmail.com
Fri Jun 9 10:15:08 UTC 2017


Hi,

At the outset I would like to mention that I do not completely understand
how type-class instance resolution works, and why it works that way. I have
tried reading up, but I don't completely understand WHY it works that way.
So, please feel free to ask me to RTFM if what I'm about to say doesn't
make any sense, although TFM doesn't make sense to me!

>From a pragmatic standpoint is there any way to express the following idea
in Haskell (or a future version of Haskell), **with minimal amount of
boilerplate**

    If a type has an instance of type-class `a`, then here's how you can
get an instance of type-class `b`

Without the ability to express this idea, you end up with a **lot** of
type-class boilerplate, (even if you use GHC Generics) eg:

    data State = data State = Inactive | Incomplete | Deleted | Trial |
Unpaid | Paid
      deriving (Eq, Show, Generic)

   instance AppEnum State where
       toString = gEnumToString
       fromString = gEnumFromString

   -- You are still forced to do the following for **every single type**
even though, conceptually, this can be driven by a rule

    instance ToJSON State where
      toJSON s = toJSON $ toString x

    instance FromJSON State where
      parseJSON (Aeson.String s) = fromString s
      parseJSON _ = fail "unexpected type"

    instance FromFIeld State where
      fromField _ mBS = case mBS of
        Nothing -> fail "not expecting a NULL/Nothing"
        (Just bs) -> pure $ fromString bs

    instance ToField State where
      toField s = toField $ toString s

I tried talking to people on IRC and also trawling StackOverflow [1] and my
take-away is essentially, that Haskell cannot express this idea. However,
my submission is, that it is a very useful idea to express and probably the
next version of the language should do something to make the lives of
programmers a little easier.

[1]
https://stackoverflow.com/questions/3213490/how-do-i-write-if-typeclass-a-then-a-is-also-an-instance-of-b-by-this-definit

-- Saurabh.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-prime/attachments/20170609/16b879a8/attachment.html>


More information about the Haskell-prime mailing list