Reputation: 41909
Learn You a Haskell presents Error
:
instance (Error e) => Monad (Either e) where
return x = Right x
Right x >>= f = f x
Left err >>= f = Left err
fail msg = Left (strMsg msg)
Hackage presents Either
:
data Either a b = Left a | Right b
If I understand correctly, then Error
is a Monad with Either
as it's a
type. Also, it looks like there's a fail
to handle exceptions.
But, I also see that there's a Control.Monad.Either
too - http://hackage.haskell.org/package/category-extras-0.53.4/docs/Control-Monad-Either.html.
Why would Control.Monad.Error
be chosen over Control.Monad.Either
, and vice-versa?
Upvotes: 7
Views: 386
Reputation: 18189
No, Error
is not a monad. Either e
is a monad, and Error e
was a typeclass prerequisite for the Monad
instance for Either e
to exist. Basically Error e
means that e
is a type which you can convert error messages into with strMsg
, which was used for Either e
's fail
method.
However, people found this requirement to have an Error e
instance just to be able to use Either e
as a monad annoying, so after LYAH was written it was actually removed. Now the instance is just
instance Monad (Either e) where
return = Right
Left l >>= _ = Left l
Right r >>= k = k r
and fail
instead uses the default from the Monad
class definition:
fail s = error s
However, the Error e
requirement is still (as of newest Haskell Platform at least) required for the monads and transformers defined in Control.Monad.Error
, while Control.Monad.Either
leaves out that requirement.
Upvotes: 11