Here's the standard Functor instance for Either a:
instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right y) = Right (f y)
adding in an as-pattern causes compilation errors when loading into GHCi:
instance Functor (Either a) where
fmap _ z@(Left x) = z -- <-- here's the as-pattern
fmap f (Right y) = Right (f y)
Couldn't match expected type `b' against inferred type `a1'
`b' is a rigid type variable bound by
the type signature for `fmap' at <no location info>
`a1' is a rigid type variable bound by
the type signature for `fmap' at <no location info>
Expected type: Either a b
Inferred type: Either a a1
In the expression: z
In the definition of `fmap': fmap _ (z@(Left x)) = z
Why doesn't this work?
If you specialize the signature of
fmaptoEither l, you get:This means that the
Left rthat you are pattern-matching on the left-hand side of your case statement must have typeEither l a. However, you can't return it as is, because you have to return anEither l b. This requires re-wrapping the left-hand value in a newLeftso that the compiler can infer that it is returning a newly mintedEitherthat might have a different type for theRightvalue.