3

I've read this question. Here is citation of accepted answer:

This instance has been added in base 4.3.x.x, which comes with ghc 7. Meanwhile, you can use the Either instance directly, or, if you are using Either to represent something that may fail you should use ErrorT monad transformer.

I want to use Either for something like this:

> (Left "bad thing happened") >>= \x -> Right (x ++ " ...")
Left "bad thing happened"

So, if one part of the computation fails, its Left is returned.

Actual question is: why should I use ErrorT monad transformer instead of Either monad? I'm a novice in Haskell, and I'm kinda afraid of monad transformters, especially when I'm already writing code inside one.

Community
  • 1
  • 1
Mark Karpov
  • 7,499
  • 2
  • 27
  • 62

1 Answers1

5

I would recommend using Either if it fits your case. An example of where it wouldn't be sufficient is if you want to perform some IO in the middle of your computation, e.g.:

x <- mightReturnLeft
y <- liftIO someIOAction
useXandY x y

In that case, Either isn't sufficient, but ErrorT would work.

Also, I'd recommend using ExceptT instead of ErrorT. ErrorT relies on the Error class which makes it more awkard to use.

Michael Snoyman
  • 31,100
  • 3
  • 48
  • 77
  • Well, in your example we have to use a monad transformer because IO monad is a one-way monad. Is there `EitherT` transformer? Does `ExceptT` work like `EitherT`? – Mark Karpov Oct 14 '14 at 10:59
  • My understanding is that ExceptT is an EitherT that is 'blessed' by being in transformers and mtl. I don't know why EitherT is an outsider, but I like the name ExceptT better. – user239558 Oct 14 '14 at 11:18
  • @Mark In practice I would probably end up using `EitherT` from [the either package](http://haddocks.fpcomplete.com/fp/7.8/20140916-162/either/Control-Monad-Trans-Either.html) since it's been around longer. The two are functionally equivalent. I referenced `ExceptT` in my answer since it also comes from `transformers`, and is what `ErrorT` has been deprecated in favor of. – Michael Snoyman Oct 14 '14 at 14:21