Reputation: 23235
In the book "Learn You a Haskell for Great Good" in the section about functors there is an example involving Either
which I don't understand:
ghci> fmap (replicate 3) (Right "blah")
Right ["blah","blah","blah"]
ghci> fmap (replicate 3) (Left "foo")
Left "foo"
Why is the latter not Left ["foo", "foo", "foo"]
?
Upvotes: 5
Views: 6028
Reputation: 28338
The Left
constructor on Either
is implemented as the "failure case". Like other functors, once this failure value enters the equation, it prevents any real computations from happening. So, when you apply fmap
to Left "foo"
it immediately returns the same "failure" value.
You can see this by looking at how Either
implements fmap
:
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
The idea here is that Left "foo"
would actually be something more descriptive, like Left "Value could not be computed"
. If you try to apply further functions to that value, you just want the "error" to get passed along intact.
If it helps, just imagine how fmap
would work on some other type where the failure case is more obvious, e.g.:
-- Maybe: failure value is `Nothing`
fmap (replicate 3) (Nothing)
This produces Nothing
, not [Nothing, Nothing, Nothing]
Upvotes: 18