Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 57 ยท Defining types

Maybe and Either

Learn how Haskell models missing values with Maybe and failures with Either, using fromMaybe, maybe, either, chaining and total functions.

Many languages use null for "no value" and exceptions for "something went wrong". Both are invisible in the types: any function might return null or throw, and you only find out when the program crashes. Haskell makes absence and failure ordinary values that appear in the type signature, so the compiler makes you deal with them.

Two types do most of the work: Maybe a for "a value or nothing", and Either e a for "a failure with information, or a success". Both are plain algebraic data types from the standard library. Real Haskell is read-only on this site; the runnable blocks are JavaScript stand-ins using tagged objects.

Maybe: a value that might be missing

HASKELL
data Maybe a = Nothing | Just a

A Maybe Int is either Nothing or Just 5. The type forces callers to handle both. Compare two list lookups:

HASKELL
head [] -- runtime exception: Prelude.head: empty list

lookup :: Eq k => k -> [(k, v)] -> Maybe v
lookup 2 [(1, "one"), (2, "two")]   -- Just "two"
lookup 9 [(1, "one"), (2, "two")]   -- Nothing

lookup is a total function: it returns a sensible result for every input. head is partial: it is undefined for the empty list. Prefer total functions. Safe versions of the partial Prelude functions are easy to write:

HASKELL
safeHead :: [a] -> Maybe a
safeHead []      = Nothing
safeHead (x : _) = Just x

safeDiv :: Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv a b = Just (a `div` b)

Consuming a Maybe

Pattern matching is the basic way to unwrap:

HASKELL
describe :: Maybe Int -> String
describe Nothing  = "no value"
describe (Just n) = "got " ++ show n

The library offers shorter tools for common cases:

HASKELL
import Data.Maybe (fromMaybe, maybe, isJust, isNothing, mapMaybe, catMaybes, fromJust)

fromMaybe 0 (Just 5)        -- 5
fromMaybe 0 Nothing         -- 0
maybe "none" show (Just 5)  -- "5"
maybe "none" show Nothing   -- "none"
mapMaybe safeHead [[1], [], [3, 4]]   -- [1,3]
catMaybes [Just 1, Nothing, Just 3]   -- [1,3]

fromMaybe supplies a default; maybe is the general eliminator that takes a default and a function for the Just case. mapMaybe maps and drops failures in one pass. Avoid fromJust: it is partial and crashes on Nothing, which defeats the purpose.

Maybe: a value or nothing

Just x The value is here.
Nothing No value, and no reason given.

Use it when absence is normal.

1 / 2

Chaining Maybe values

Real programs combine several lookups, any of which might fail. Nested pattern matching gets ugly:

HASKELL
-- find a user's city, if the user and the address both exist
userCity :: Int -> Maybe String
userCity uid = case lookup uid users of
  Nothing   -> Nothing
  Just user -> case address user of
    Nothing   -> Nothing
    Just addr -> Just (city addr)

The pattern "if Nothing, stop; otherwise pass the value on" is captured by >>= (bind), so the same function becomes:

HASKELL
userCity uid = lookup uid users >>= address >>= \addr -> Just (city addr)

or even fmap city (lookup uid users >>= address). If a step returns Nothing, the rest is skipped. Why this works is the subject of Functors and Monads; for now treat >>= as "and then, if that worked".

JS Maybe with tagged objects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Either: failure with a reason

Nothing says that something is missing but not why. When callers need the reason, use Either:

HASKELL
data Either e a = Left e | Right a

By convention, Left carries the error and Right carries the success (a handy mnemonic is that "right" means "correct"). The type has two parameters, so Either String Int is "an error message or an Int".

HASKELL
parseAge :: String -> Either String Int
parseAge s = case reads s of
  [(n, "")]
    | n < 0     -> Left "age cannot be negative"
    | n > 150   -> Left "age is unrealistic"
    | otherwise -> Right n
  _ -> Left ("not a number: " ++ s)

parseAge "42"    -- Right 42
parseAge "-3"    -- Left "age cannot be negative"
parseAge "abc"   -- Left "not a number: abc"

Errors can be strings, as here, but real programs usually define an error type so callers can react to specific cases:

HASKELL
data ValidationError = EmptyName | BadAge String | TooYoung Int
  deriving (Show, Eq)

Consuming and chaining Either

either is the eliminator, like maybe: it takes one function for each case.

HASKELL
either length (* 2) (Left "oops")   -- 4
either length (* 2) (Right 21)      -- 42

import Data.Either (lefts, rights, partitionEithers)
partitionEithers [Left "a", Right 1, Right 2, Left "b"]
-- (["a","b"],[1,2])

Chaining works exactly as for Maybe: the first Left stops the computation and is returned unchanged, while a Right passes its value on.

HASKELL
data Person = Person String Int deriving Show

mkPerson :: String -> String -> Either String Person
mkPerson name ageText = do
  n <- validateName name
  a <- parseAge ageText
  Right (Person n a)

This do block is explained in do-Notation Demystified. If validateName returns Left, the whole result is that Left and parseAge never runs. To collect all errors instead of stopping at the first, you need applicative-style validation, which comes in Applicative Functors.

JS Either with early exit

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Choosing between Maybe, Either and exceptions

Situation Tool
A value may legitimately be absent (lookup, first element) Maybe
The caller needs to know why it failed Either with an error type
A bug or violated precondition ("impossible" cases) error / exceptions
Failures in IO such as a missing file IO exceptions (see Exceptions and Error Handling)

Converting between them is simple: maybe (Left err) Right turns a Maybe into an Either, and either (const Nothing) Just goes the other way, throwing the reason away.

Avoiding partial functions

A partial function is one that crashes on some inputs. The Prelude contains a few well-known ones: head, tail, last, init, (!!), fromJust, maximum [] and read on bad input. Instead:

  • use pattern matching, Maybe returning versions, or listToMaybe from Data.Maybe;
  • use readMaybe from Text.Read instead of read;
  • let -Wall and -Wincomplete-patterns warn about missing cases, and consider HLint to flag partial functions.
HASKELL
import Text.Read (readMaybe)

readMaybe "42"  :: Maybe Int   -- Just 42
readMaybe "4x"  :: Maybe Int   -- Nothing

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fromMaybe 10 Nothing return?

    fromMaybe returns the default when given Nothing and unwraps the value for Just.
  2. 2. In Either String Int, which constructor conventionally holds the error?

    By convention Left carries the failure and Right carries the success.
  3. 3. What happens in a chain of Either steps when the first step returns Left?

    Chaining with >>= (or do) short-circuits at the first Left and passes it through unchanged.
  4. 4. Why is head considered a partial function?

    head [] raises an exception because it has no valid result; a total version returns Maybe.
  5. 5. Which function turns the text "42" into Just 42 safely?

    readMaybe from Text.Read returns Nothing on bad input instead of throwing.

Summary

  • Maybe a is Nothing or Just a; use it when a value may legitimately be missing.
  • Either e a is Left e (failure with a reason) or Right a (success).
  • fromMaybe, maybe and either unwrap values; mapMaybe, catMaybes and partitionEithers work on lists.
  • Chaining with >>= or do stops at the first Nothing or Left.
  • Prefer total functions (lookup, readMaybe) to partial ones (head, fromJust, read).

Next: Recursive Data Types and Trees.