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

Brandon Michael Moore brandon at its.caltech.edu
Thu Mar 11 16:56:41 EST 2004



On Thu, 11 Mar 2004 Ben_Yu at asc.aon.com wrote:
>
> Thanks! Oleg.
>
> This works and it looks nice!
>
> And now, my code can be like:
>
> class FwdSig d where
>   (forall a. Sig a => a -> w) -> d -> w
>
> All the types that supports such forwarding are instances of FwdSig.
>
> My Def type is:
>
> instance FwdSig Def where
>   fwd f (ClassDef c) = f c
>   fwd f (ProtDef p) = f p
>
> instance Sig Def where
>   getName = fwd getName
>   getMethods = fwd getMethods
>   ...
>
> My Native type is:
>
> instance FwdSig Native where
>   fwd f (NativeSignature s) = f s
>   fwd f (NativeProtocol p) = f p
>
> instance Sig Native where
>   getName = fwd getName
>   getMethods = fwd getMethods
>   ...
>
> Many annoying forwarding functions are gone.
>
> The only thing that I hope to be better is this "getXXX = fwd getXXX" piece
> of code. Is it possible to reuse the same piece of code for both Native and
> Def and any other possible types?

I'm not as handy with the type system as Oleg, but I can help out here.

The problem with your new instance is that if the compiler is trying to
see if Native is an instance of Sig, it can start with the declaration Sig
Native, or the declarations FwdSig a => Sig a, both of which could
potentially derive an instance of Sig Native.

Additionally passing the -fallow-overlapping-instances flag will permit
you to compile a program where instances overlap like this, and will
select the most specific matching instance (looking only at the head).
Your code is fine.

Brandon

> Inspired by your generic code, I wrote such thing:
>
> instance FwdSig d => Sig d where
>   getName = fwd getName
>   getMethods = fwd getMethods
>   ...
>
> However, my ghc complains about the use of "Sig d".
>
> I followed its recommendation and put -fallow-undecidable-instances flag
> with the surprise that the "FwdSig d=>Sig d" instance declaration conflicts
> with my other "instance Sig XXX" declarations.
>
> Surely this is not a serious problem, I can live with repeating the
> "getXXX=fwd getXXX" several times. Just curious about how further this can
> go.
>
> Ben.




More information about the Haskell mailing list