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.
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
Either some of it is regained.
Either gives functions the ability to return one of two values, a