Po ćwiczeniach w Typeclassopedia, próbowałem zaimplementować instancję Functor for Either. Moja pierwsza próba była następująca:Niezgodność typu podczas pisania instancji Functor dla
instance Functor (Either a) where
fmap f (Right a) = Right (f a)
fmap _ left = left
Nasuwa się następujące kompilacji błąd:
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
Najprostszym sposobem rozwiązania jest to, aby zastąpić drugą definicję fmap
jak następuje:
instance Functor (Either a) where
fmap f (Right a) = Right (f a)
fmap _ (Left a) = Left a
Czy ktoś może mi wyjaśnić, dlaczego błąd został rozwiązany przez bezpośrednie dopasowanie do wzorca w drugiej definicji fmap
?