Pregunta

Why doesn't this code work:

class Foo a b c | a b -> c where
  foo :: a -> b -> c

instance Foo Int Int Int where
  foo a b = a + b  

ghci > foo 4 4  -- This produces run time error

And by using functional dependency, why the following code produces compile time error:

instance Foo Float Float Int where
  foo a b = a + b

I know that the above instance is an crazy example, but isn't the aim of functional dependency to help the type checker in resolving these issues ?

¿Fue útil?

Solución

Actually it did resolve the ambiguity. The problem is that 4 :: Num a => a so GHC can't decide that you want to use foo :: Int -> Int -> Int. Now if instead you did

foo (4 :: Int) (4 :: Int)
> 8

Since now it is clear which instance we want to use. To make this clearer, suppose we had

class Foo a b c | a -> b, a -> c where
  ...

Now we could do

foo (4 :: Int) 4
> 8

since once GHC has filled in all the type variables not on the right side of an ->, it can fill in the rest.

Otros consejos

instance Foo Float Float Int where
    foo a b = a + b

This is a error even without the functional dependency. If a and b are Float, then a + b is a Float, not an Int.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top