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?
In Haskell either is used to represent the possibility of two values. Either is used to represent two values that can be correct or error. It has two constructors also which are named Left and Right. These constructors also represent and show some purpose either in Haskell.
The Either type is sometimes used to represent a value which is either correct or an error; by convention, the Left constructor is used to hold an error value and the Right constructor is used to hold a correct value (mnemonic: "right" also means "correct").
In Error handling we have two possible paths either a computation succeeds or fails. The imperative way to control the flow is using exceptions and a try/catch block.
On the one hand, an error is a programming mistake such as a division by zero, the head of an empty list, or a negative index. If we identify an error, we remove it. Thus, we don't handle errors, we simply fix them. In Haskell, we have error and undefined to cause such errors and terminate execution of the program.
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.
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