Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deduction types fail in Haskell.

Tags:

haskell

class (Eq a) => My a where
    f:: (a,a) -> (a,a)

instance My Int where
    f (a,b) = (a,b)

instance My Char where
    f (a,b) = (a,b)

And "specialization for the pair". It makes compilation error and I don't know why. Please help to repair it and explain me why it is error.

instance (My a, My b) => My (a,b) where
    f ((a,b), (c,d)) = ( (f (a,b)), (f (c,d)) )

Error:

test.hs:11:31:
    Could not deduce (a ~ b)
    from the context (Eq (a, b), My a, My b)
      bound by the instance declaration at test.hs:10:10-33
      `a' is a rigid type variable bound by
          the instance declaration at test.hs:10:10
      `b' is a rigid type variable bound by
          the instance declaration at test.hs:10:10
    Expected type: (a, b)
      Actual type: (a, a)
    In the return type of a call of `f'
    In the expression: (f (a, b))
    In the expression: ((f (a, b)), (f (c, d)))
Failed, modules loaded: none.
like image 928
Gilgamesz Avatar asked Dec 08 '25 09:12

Gilgamesz


2 Answers

The error message is spot on. In your tuple instance, you have

   f :: ((a,b), (a,b)) -> ((a,b), (a,b))

where a and b are in general different types. But for any instance, f can only operate on (a,a) tuples, i.e. you need type equality a ~ b. Thus

instance (My a) => My (a,a) where
  f (ab, cd) = (f ab, f cd)

would work... or, actually, I remember this causes some problems (forgot what) and you should better make the equality constraint explicit

instance (My a, a~b) => My (a,b) where
like image 57
leftaroundabout Avatar answered Dec 10 '25 10:12

leftaroundabout


You might want the following instance instead:

instance (My a, My b) => My (a,b) where
    f ((a, b), (c, d)) = case (f (a, c), f (b, d)) of
      ((a1, a2), (b1, b2)) -> ((a1, b1), (a2, b2))

Above (a, c) :: (a, a) and (b, d) :: (b, b), so we apply f to those. We get back a pair of type ((a, a), (b, b)) which we reorder so to obtain ((a, b), (a, b)).

like image 41
chi Avatar answered Dec 10 '25 11:12

chi