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.
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
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)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With