16

I was under the impression that there was an instance for Either a somewhere, but I can't seem to find it. I have tried importing Control.Monad, Control.Monad.Instances and Data.Either as shown

module Main where

import Control.Monad
import Data.Either
import Control.Monad.Instances

test :: [Either a b] -> Either a [b]
test = sequence

main = return ()

but ghc tells me that it could not deduce (Monad (Either a)). Adding

instance Monad (Either a) where
    return = Right
    Right b >>= f = f b
    Left a >>= _ = Left a

makes the code compile, but this instance declaration seems so general that it doesn't make sense to me if it isn't already out there in some standard module. If it is, where should I look to find it, and if it isn't, is there then a reason for this?

-------------- EDIT ---------------

Be aware that I now think that the answer by user31708 below ("As of base 4.6, the instance is in Data.Either itself.") is currently the correct answer. I am not sure of the proper protocol of reassigning the selected answer in this case, where the selected answer was the correct answer at the time that the question was asked, so I have left it as it is. Please correct me, if there is another guideline for this.

Boris
  • 5,094
  • 4
  • 45
  • 71
  • The reason for the stupid error constraint is to make `fail` work "properly." Yet another reason why the `fail` method is a failure. – sclv Feb 25 '11 at 00:53
  • 1
    @sclv: I'm not sure I follow. The reason I was looking for was why there was no standard (Either a) monad instance declaration. – Boris Feb 25 '11 at 01:50

4 Answers4

18

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.

Alvivi
  • 3,263
  • 3
  • 26
  • 28
  • 3
    In the meantime Control.Monad.Trans.Error in transformers provides an identical instance for backwards compatibility if used with an older version of base, so if you import that you can work across versions. – Edward Kmett Mar 01 '11 at 02:02
6

As of base 4.6, the instance is in Data.Either itself.

user31708
  • 630
  • 5
  • 11
5

There is not an instance for Either a, but there is for Either String in Control.Monad.Error. (Actually, it's for Error e => Either e, IIRC).

wnoise
  • 9,764
  • 37
  • 47
1

I believe there's something in Control.Monad.Error - don't have anything to check, though.

Anon.
  • 58,739
  • 8
  • 81
  • 86