Following the exercises in the Typeclassopedia, I tried to implement an instance of Functor for Either. My first attempt was the following:
instance Functor (Either a) where
fmap f (Right a) = Right (f a)
fmap _ left = left
This raises the following compile-time error:
functor.hs:7:17:
Couldn't match type ‘a1’ with ‘b’
‘a1’ is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> Either a a1 -> Either a b
at functor.hs:6:3
‘b’ is a rigid type variable bound by
the type signature for
fmap :: (a1 -> b) -> Either a a1 -> Either a b
at functor.hs:6:3
Expected type: Either a b
Actual type: Either a a1
Relevant bindings include
left :: Either a a1 (bound at functor.hs:7:10)
fmap :: (a1 -> b) -> Either a a1 -> Either a b
(bound at functor.hs:6:3)
In the expression: left
In an equation for ‘fmap’: fmap _ left = left
The easiest way to solve this is to replace the second definition of fmap like the following:
instance Functor (Either a) where
fmap f (Right a) = Right (f a)
fmap _ (Left a) = Left a
Can someone explain me why the error is solved by explicitly pattern-matching in the second definition of fmap?