proposal #4095: add Applicative instance for Either
gale at sefer.org
Tue Jun 1 14:35:40 EDT 2010
>> The Either Monad/Applicative provides multi-level exit
>> from nested complex computations.
Evan Laforge wrote:
> Can you give a specific example? I'm trying to think of how this is
> different from the normal exceptional escape mechanism.
> I use Either as a Maybe + info all the time, but I think you're
> talking about something more sophisticated here.
No something very simple.
Here's a contrived example that computes the number
of days in a month:
daysInMonth :: Int -> Int -> Int
daysInMonth month year = either id id $ do
when (month `elem` [4,6,9,11]) $ Left 30
when (month == 2) $ do
when (year `mod` 4 /= 0) $ Left 28
when (year `mod` 400 == 0) $ Left 29
when (year `mod` 100 == 0) $ Left 28
If the answer becomes known somewhere in
the middle of the calculation, Left causes the
calculation to exit at that point and return the
given answer. If the calculation makes it all
the way to the end without exiting, the answer
This is exactly the same way that Either works
for exception handling - except we don't require
an Error instance for the Left type.
More information about the Libraries