[Haskell] What is the best way to write adapters?

Ben_Yu at asc.aon.com Ben_Yu at asc.aon.com
Thu Mar 11 11:34:36 EST 2004


I have a class:

class Sig a where
  getName :: a -> Id
  getParents :: a -> [TypeExp]
  getMethods :: a -> [MethodDef]
  getFields :: a -> [FieldDef]

and a few data structures that are instances of Sig.

They are ClassDef, ProtocolDef, SignatureDef, etc.

Now I have a type Def defined as:

data Def = DefClass ClassDef | DefProtocol ProtocolDef | DefSignature

And I want to make Def also an instance of Sig.

The code is currently like this:

instance Sig Def where
  getName (DefClass c) = getName c
  getName(DefProtocol p) getName p
  getName(DefSignature s) = getName s
  getParents(DefClass c) = getParents c
  getParents(DefProtocol p) = getParents p
blah blah blah...

But this seems very annoying.

If I have 4 different constructors in Def, and 5 methods of class Sig,
(Please bear with me if I'm using some OO terminology because I'm still a
new FP programmer), I'll have to write 4*5=20 forwarding functions.

I was trying to write something like:
getSig:: Sig a => Def -> a
getSig (DefClass c) = c
getSig (DefProtocol p) = p

But this does not compile.

So, is there any nice way to save me from typing the x*y forwarding



This message is intended only for the addressee and may contain information
that is confidential or privileged. Unauthorized use is strictly prohibited
and may be unlawful. If you are not the intended recipient, or the person
responsible for delivering to the intended recipient, you should not read,
copy, disclose or otherwise use this message, except for the purpose of
delivery to the addressee. If you have received this email in error, please
delete and advise us immediately.

More information about the Haskell mailing list