Dopo gli esercizi nella Typeclassopedia, ho provato a implementare un'istanza di Functor per Either. Il mio primo tentativo è stato il seguente:Tipo non corrispondente durante la scrittura di un'istanza Functor per O
instance Functor (Either a) where
fmap f (Right a) = Right (f a)
fmap _ left = left
Ciò solleva la seguente fase di compilazione errore:
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
Il modo più semplice per risolvere questo è quello di sostituire la seconda definizione di fmap
come la seguente:
instance Functor (Either a) where
fmap f (Right a) = Right (f a)
fmap _ (Left a) = Left a
Qualcuno può spiegarmi perché l'errore viene risolto esplicitamente con il modello di corrispondenza nella seconda definizione di fmap
?