Either
monadicon.icon
Using Either, we can use Left to encode errors, and Right to encode successful results.
code:eitherMonadInstance.hs
instance Monad (Either e) where
return :: a -> Either e a
return x = Right x
(>>=) :: Either e a -> (a -> Eithere b) -> Either e b
f >>= g = case f of
Left e -> Left e
Rightx -> g x
We can abstract completely from the definition of the underlying Either type if we define functions to throw and catch errors.
code:throwerror.hs
throwError :: e -> Either e a
throwError e = Left e
catchError :: Either e a -- Computation
-> (e -> Either e a) -- Handler
-> Either e a
catchError f handler = case f of
Left e -> handler e
Right x -> Right x