[Haskell-cafe] Why Either = Left | Right instead of something like Result = Success | Failure

Anton van Straaten anton at appsolutions.com
Fri May 28 10:48:48 EDT 2010


Ionut G. Stan wrote:
> Thank you all for the answers. It seems that a recurring reason is that 
> being defined as a general type, Either can be used not only to handle 
> errors, but choice in general. This, however, seems to make Either to 
> overloaded in my opinion. If I decide that I want to use Either as a way 
> to signal error, but a third party accepts Either for something 
> different, then things will probably not work.

It's unlikely that the types would be compatible, unless you're using a 
type like Either String String.  In that case, the solution may not be 
to switch to something other than Either, but rather to make the type 
more precise, like Either MyError MyValue, which can't be confused with 
other uses of Either.

Keep in mind that a major point of the polymorphic type system in a 
language like Haskell is to be able to write typed code once and reuse 
it as widely as possible, so you should expect something as basic as 
choice between two alternatives to be represented by a very general type.

A big advantage of using Either in a case like this is that any code 
written to operate on a general enough version of that type, such as 
"Either a b", may work just fine on your particular use of Either.  That 
includes code which implements error monads, like these:

http://hackage.haskell.org/packages/archive/transformers/0.2.1.0/doc/html/Control-Monad-Trans-Error.html
http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Error.html

or e.g. the Either utilities in MissingH:

http://hackage.haskell.org/packages/archive/MissingH/1.1.0.3/doc/html/Data-Either-Utils.html

By using Either, you're using the natural Haskell type for representing 
choice between two alternatives, that allows you to benefit from much of 
the code that's been written to use that type.

> I have little experience with Haskell, but I haven't seen Either used in 
> contexts other than error/success. If you could point me to some piece 
> of code that uses it in a different way it would be great.

Choice between two alternatives is a pretty common requirement - think 
of it as the datatype equivalent of an 'if' expression.  As a result, 
it's used quite a lot.

There's an example in the main GHC driver program, 
http://darcs.haskell.org/ghc/ghc/Main.hs :

type Mode = Either PreStartupMode PostStartupMode
type PostStartupMode = Either PreLoadMode PostLoadMode

Notice that it's not possible to confuse those types with something 
else.  Further, using an alias defined with 'type', as in the above 
example allows you to name your type something relevant to your program, 
without losing the benefits of using a general type like Either.

Anton



More information about the Haskell-Cafe mailing list