I am currently reading the excellent "Learn You a Haskell for Great Good", and 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"]
?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With