Either and recoverable errors

An error with a reason

Maybe says that something is missing and nothing about why. Either a b has the same shape with two type parameters: Left x carries a failure of type a, Right y carries a success of type b. The convention is Left for the error and Right for the value, and the type tells the two apart.

data Either a b = Left a | Right b

A function that validates returns Either String Int: a message on the left, the accepted value on the right. The caller gets both the possibility of failure and the reason, and the compiler still requires both branches.

A validation function

Guards are the natural way to write a validator, one per rule, with the successful case last:

module Main (main) where validateAge :: Int -> Either String Int validateAge n | n < 0 = Left "negative age" | n > 130 = Left "age above 130" | otherwise = Right n main :: IO () main = do print (validateAge 30) print (validateAge (-1)) print (validateAge 200)

ghc -Wall -O1 -o either either.hs
./either

Right 30
Left "negative age"
Left "age above 130"

The output is the derived Show of the two constructors. Note that the value is printed with its constructor, which is what tells a reader of a log which case happened; a function that should print a message to a user pattern matches and formats it.

partitionEithers

A list of results is a common shape: validate every field, and report all the failures at once. partitionEithers splits the list into the lefts and the rights, which is the missing half of mapMaybe:

module Main (main) where import Data.Either (partitionEithers) type Field = (String, String) required :: Field -> Either String String required (key, "") = Left ("missing " ++ key) required (_, value) = Right value main :: IO () main = do let fields = [("name", "Ada"), ("email", ""), ("city", "London")] print (partitionEithers (map required fields)) print (map required fields)

ghc -Wall -O1 -o partition partition.hs
./partition

(["missing email"],["Ada","London"])
[Right "Ada",Left "missing email",Right "London"]

The first line is the useful one: errors and values separated, each in its own list, ready to be printed or counted. The second line shows the same data in order, which is what a per-field report needs. Both come from the same list and neither throws: a missing field is a value like any other.

Why the error is in the type

An exception can be thrown from anywhere and caught anywhere, so a signature says nothing about it. Either puts the failure in the return type, which has three consequences the course keeps using:

The difference between the two is what the failure carries. Use Maybe when absence is the whole story, and Either when a caller needs to know what went wrong. The exceptions of Control.Exception, later in the course, are for failures that cannot be answered in the type: a closed file, a broken pipe, a signal.

Exercises

  1. Write validateEmail :: String -> Either String String that rejects a string without an @.
  2. Combine two validations with a case and then with >>=, and print both.
  3. Use partitionEithers on a list of three ages, two of them invalid, and print the two lists.
  4. Write either length (const 0) over a Either String String and explain the result.
  5. Change validateAge to return Either [String] Int and explain what a list of errors makes possible.
  6. Explain when Maybe is the better type and when Either is.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Left "bad" represent in Either String Int?

    Answer

    A failure carrying the message "bad"

    Left is the error side of Either and carries the error value.

  2. What is the type of Right 3 in a validation returning Either String Int?

    Answer

    Either String Int

    Right wraps the success value, so the whole expression has the Either type.

  3. What does validateAge (-1) return in the lesson program?

    Answer

    Left "negative age"

    The first guard holds, so the function returns the Left with its message.

  4. What does partitionEithers [Right 1, Left "e", Right 2] return?

    Answer

    ([1,2],["e"])

    The pair is (lefts, rights), so the values and the error are separated in that order.

  5. What does this program print? module Main (main) where main :: IO () main = print (either length (const 0) (Left "abc"))

    Answer

    3

    For a Left, either applies its first function, which is length on the three-character string.

  6. Why does a caller of a function returning Either have to handle the Left?

    Answer

    The result is an Either, and using it as a plain value does not type check

    The failure is in the type, so the only ways to proceed are matching, mapping or collapsing it.

  7. Which type should a lookup that may fail with a reason use?

    Answer

    Either String a

    Maybe carries no reason; Either with a message keeps the explanation in the result.

  8. What does this program print? module Main (main) where validate :: Int -> Either String Int validate n | n > 0 = Right n | otherwise = Left "not positive" main :: IO () main = print (validate 5)

    Answer

    Right 5

    The guard holds and the function returns Right with the value.

  9. How does a chain of Either computations stop at the first failure?

    Answer

    The first Left short-circuits the rest of the chain

    Either is a monad whose bind returns the first Left unchanged; collecting all errors needs another type.

  10. What is the difference between Maybe and Either for errors?

    Answer

    Either carries a reason for the failure, Maybe only its absence

    Both model a failure, and Either adds a value that says what went wrong.

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev