All Articles

The Either Datatype

Consider a program which returns a string.

helloWorld cond =
    if cond
    then "Hello world"
    else "Good bye world"

Due to Haskell’s type inference, there is no way for helloWorld to alter its return type; the value is bound to a String. Which means that the following program is invalid.

helloWorld cond =
    if cond
    then "Hello world"
    else cond -- Bool is not a string

Since Haskell is a strong statically typed programming language, it will not allow multiple return types. Instead, a type which represents multiple types is needed.

Using Either

Either in Haskell allows functions to return one of two types. It is defined as:

data Either a b = Left a | Right b

Values that are Left represent the “wrong” output, whereas Right symbolizes the “correct” return value. However, Haskell does not enforce this, it is just a convention.

The previous example will work once Haskell infers that the return type is Either Bool String.

helloWorld2 cond =
    if cond
    then Right "Hello world"
    else Left cond

Limitations

Either is limited in the sense that it only allows two types to be returned. In other programming languages (Racket, JavaScript, Python, etc.), any kind of return types is allowed. By being strict, Haskell knows beforehand errors that may arise as a result of incorrect types being passed around, but in the process loses flexibility. By using Either some of it is regained.

Summary

Either gives functions the ability to return one of two values, a Left or Right value.

Published 13 Dec 2015