To add to Daniel's excellent answer, there are a couple points I'd like to make:
First, here's the Applicative instance:
instance Applicative (Either e) where
pure = Right
Left e <*> _ = Left e
Right f <*> r = fmap f r
You can see that this is 'short-circuiting' -- as soon as it hits a Left
, it aborts and returns that Left. You can check this with poor man's strictness analysis:
ghci> (++) <$> Left "Hello" <*> undefined
Left "Hello" -- <<== it's not undefined :) !!
ghci> (++) <$> Right "Hello" <*> undefined
*** Exception: Prelude.undefined -- <<== undefined ... :(
ghci> Left "oops" <*> undefined <*> undefined
Left "oops" -- <<== :)
ghci> Right (++) <*> undefined <*> undefined
*** Exception: Prelude.undefined -- <<== :(
Second, your example is slightly tricky. In general, the type of the function and the e
in Either e
are not related. Here's <*>
s type:
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
If we make the substitution f
-->> Either e
, we get:
(<*>) :: Either e (a -> b) -> Either e a -> Either e b
Although in your example, e
and a
match, in general they won't, which means you can't polymorphically implement an Applicative instance for Either e
which applies the function to a left-hand argument.