🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Either Values

Either is a type that holds a value on its left side or its right side. By convention, Left holds a failure message and Right holds a success result.

Right holds a success result

A result binding can hold Right 5 as a successful answer. The type line shows the failure type first and the result type second.

result :: Either String Int
result = Right 5

main :: IO ()
main = print result

Left holds a failure message

A result binding can hold a message in Left instead of a number. Printing it keeps the message in double quotes.

result :: Either String Int
result = Left "Cannot divide by zero"

main :: IO ()
main = print result

Division that checks for zero

The checkedDiv function returns Left when the second number is 0. For other second numbers, it returns the division result inside Right.

checkedDiv :: Int -> Int -> Either String Int
checkedDiv _ 0 = Left "Cannot divide by zero"
checkedDiv x y = Right (div x y)

main :: IO ()
main = print (checkedDiv 10 2)

Example

checkedDiv :: Int -> Int -> Either String Int
checkedDiv _ 0 = Left "Cannot divide by zero"
checkedDiv x y = Right (div x y)

describe :: Either String Int -> String
describe (Left msg) = "Error: " ++ msg
describe (Right n) = "Result is " ++ show n

main :: IO ()
main = putStrLn (describe (checkedDiv 10 0))

Key points

  • Either a b: a type that holds a Left value of type a or a Right value of type b.
  • Left: the side that holds a failure message by convention.
  • Right: the side that holds a success result by convention.
  • Checked function: a function that returns Either so a risky step can report failure as a value.
  • Pattern matching: matching Left and Right lets a function handle failure and success in one place.

In this example, checkedDiv 10 0 matches the zero pattern and returns Left "Cannot divide by zero". The describe function matches that Left value and adds the word Error before the message. The main action prints the finished text.

Note

Right also means correct in everyday English, which helps mark the success side.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

In the convention used in this lesson, what does a Left value hold?