HASKELL / CHAPTER 09
Either and explanatory failures
IntermediateMake failure information part of a total result type.
By the end of this chapter
- Distinguish Left errors from Right values
- Sequence dependent checked operations
- Preserve failure details without sentinel values
The idea
Maybe represents absence, while Either can also carry an explanation. A result such as Either String Integer makes both the error information and successful value visible in the type. Pattern matching forces callers to consider the alternatives instead of treating a special integer as a failure sentinel that might collide with valid data.
Dependent checked computations can be sequenced so that a Left propagates and later successful work is skipped. This expresses a failure policy rather than throwing a hidden exception from an otherwise ordinary-looking function. Keep error messages or error constructors meaningful enough for the layer that handles them. A total interface should also account for input boundaries such as a zero divisor before performing the unsafe operation.
divide :: Integer -> Integer -> Either String Integer
divide _ 0 = Left "zero divisor"
divide a b = Right (a `div` b)
main = do
print (divide 9 2)
print (divide 9 0)Right 4 Left "zero divisor"
The zero case is handled before division, and the successful branch contains its integer quotient explicitly.
Try it yourself
Chain two validated numeric steps, preserving the first explanatory failure.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING