jamshidh
jamshidh

Reputation: 12060

Haskell Inferred instance declaration on inherited classes

I've seen cases of chains of Haskell classes that all "extend" each other (see for example, the widget/container/etc classes in gtk2hs)

class Class1 a where....
class (Class1 a)=>Class2 a where....
class (Class2 a)=>Class3 a where....
....and so on....

where all the class functions have default values that depend on one Class1 function. This works great, but makes for a really ugly "instantiation" of ClassN

Instance Class1 Object where
    func x = ....
Instance Class2 Object
Instance Class3 Object
Instance Class4 Object
Instance Class5 Object
....and so on....

(I've seen code just like this in popular hackage libraries, so I'm pretty sure that at the time of the writing of the code this was a proper way to do this).

My question- Are there any newer GHC extensions that would clean this up. I've looked a bit and haven't found any. Ideally, all you really need is to decleare Object as an instance of ClassN, and give the Class1 function, the rest would be inferred.

[preemptive snarky comment :)- This indicates an "object oriented" way of thinking, you should really learn how to program functionally.

My response- I agree it is very object oriented, but code like this exists in the ecosystem today, and might very well be needed, GUI libs like gtk2hs, for example. From a practical viewpoint I need to write code like this sometimes, and I just want to simplify it.]

Upvotes: 1

Views: 113

Answers (1)

wit
wit

Reputation: 1622

It is a discussed proposal to add Synonym Instances.

For example it would be possible to write next code:

type Stringy a = (Read a, Show a)

instance Stringy a where
     read = ...
     show = ...

in this case it would be possible to declare

type ClassAll a = (Class1 a, Class2 a, Class3 a, Class4 a)

instance ClassAll a where
   foo = ...

But for now, type constraint could be used in function's signatures only, not in instances.

UPDATED

As Vittor mentions, you can find proposal here: Multi-headed instance declarations The original proposal is a part of class aliases proposal

Upvotes: 3

Related Questions