[Haskell-cafe] More newbie typeclass confusion...

Luke Palmer lrpalmer at gmail.com
Sat Dec 29 22:57:01 EST 2007


On Dec 30, 2007 3:43 AM, Jonathan Cast <jonathanccast at fastmail.fm> wrote:
> On 29 Dec 2007, at 9:31 PM, alex wrote:
>
> > Hi there.
> >
> > If someone can tell me why I am getting type ambiguity
> > in the following code:
> >
> >     class (Ord s, Num s) => Scalar s where
> >         zero :: s
> >
> >     class Metric m where
> >         delta   :: Scalar s => m -> m -> s

Just to clear up common confusion: the caller chooses s here, not the
delta function.  So
delta has to work for any choice of s the caller chooses (as long as
it is an instance of
Scalar).

> >         (=~)    :: m -> m -> Bool
> >         (/~)    :: m -> m -> Bool
> >
> >         (=~) a b    = (delta a b) <= zero

What instance of Scalar do you want delta to return here?  There's no
way for the compiler
to deduce that information.

What you probably want is a fundep or associated type, associating a
single choice of scalar
for each metric:

class (Scalar (Field m)) => Metric m where
    type Field m :: *
    delta :: m -> m -> Field m
    ...

instance Metric Double where
    type Field Double = Double
    delta = (-)
    ...

Luke


More information about the Haskell-Cafe mailing list