문제

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 ?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top