Haskell ambiguous type variables with functional dependencies

I played with FunctionalDependencies-Extension Haskell along with MultiParamTypeClasses. I have defined the following:

class Add a b c | a b -> c where
    (~+) :: a -> b -> c
    (~-) :: a -> b -> c
    neg :: a -> a
    zero :: a

which works fine (I tried to use instances for Int and Double with the ultimate goal of adding Int and Doubles without explicit conversion).

When I try to define default implementations for neg or (~ -) as follows:

class Add ...
    ...
    neg n = zero ~- n

GHCi (7.0.4) tells me the following:

Ambiguous type variables `a0', `b0', `c0' in the constraint:
  (Add a0 b0 c0) arising from a use of `zero'
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `(~-)', namely `zero'
In the expression: zero ~- n
In an equation for `neg': neg n = zero ~- n

Ambiguous type variable `a0' in the constraint:
  (Add a0 a a) arising from a use of `~-'
Probable fix: add a type signature that fixes these type variable(s)
In the expression: zero ~- n
In an equation for `neg': neg n = zero ~- n

I think I understand the problem here. The GHC does not know which zero to use, since it can be any zero giving something, which in turn is fed into ~-, of which we only know what it has ain the correct argument and gives a.

, , , - :

neg n = (zero :: Add a b c) ~- n

, a, b c abc , ab c, , ?

+3
2

neg zero , :

class Zero a where
    neg :: a -> a
    zero :: a

class Zero a => Add a b c | a b -> c where
    (~+) :: a -> b -> c
    (~-) :: a -> b -> c

, , zero :: Int zero Add Int Int Int zero Add Int Double Double, , , re .

( , zero from Add Int Int Int zero from Add Int Double Double , , - Add Int Char Bool zero .)

, .

+6

zero Add. ; Haskell , , .

, zero , . : " a, b, c a", ; b c, , b c , , Add Int Int Int Add Int (Maybe String) Boat, Haskell , . "" () :

class Invertible a where
  invert :: a -> a

neg :: Invertible a => a -> a
neg = invert

class Zero a where
  zero :: a

class Add a b c | a b -> c where
  (~+) :: a -> b -> c
  (~-) :: a -> b -> c

, Invertible zero Add; , , ? neg ~+; , (, )? .

+3

All Articles