[Haskell-beginners] multi-parameter typeclass with default implementation

Ben Gamari bgamari.foss at gmail.com
Mon Aug 19 22:59:42 CEST 2013


TP <paratribulations at free.fr> writes:

> Hi,
>
> I struggle with a dummy example using a multi-parameter typeclass containing 
> a default implementation for a function:
>
> ---------------------------------------
> {-# LANGUAGE MultiParamTypeClasses #-}
>
> class Foo a b where
>
>     bar :: a -> Int
>
The problem is in this declaration, which does not mention the type
"b". This makes it impossible for the compiler to infer which instance
to use when "bar" is used. This is what the compiler is trying to tell
you when it says "The type variable `b1' is ambiguous".

As far as I know, you'd need to do something like this to accomplish
what you are after,

    {-# LANGUAGE MultiParamTypeClasses, DefaultSignatures #-}
    
    class Bar a where
        bar :: a -> Int
    
    class FooBar a b where
        foobar :: a -> b -> Int
        default foobar :: Bar a => a -> b -> Int
        foobar avalue bvalue = bar avalue
    
    instance Bar Int where
        bar i = 5
    instance FooBar Int Int
    
    main = do
        print $ bar (4::Int)
        print $ foobar (5::Int) (2::Int)
        
                                
Cheers,

- Ben
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 489 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20130819/11e10321/attachment.pgp>


More information about the Beginners mailing list