typestar

Maybe & Either in Haskell

Maybe reports a missing value as Nothing; Either carries a reason on the Left.

module Pantry where

import Data.Maybe (fromMaybe)

-- lookup answers with Nothing rather than crashing on a missing key
shelf :: [(String, Int)]
shelf = [("lentils", 4), ("rice", 12)]

-- fromMaybe supplies a default for Nothing and unwraps a Just
onHand :: String -> Int
onHand item = fromMaybe 0 (lookup item shelf)
-- maybe does the same but runs a function over the Just on the way out
report :: String -> String
report item = maybe "not stocked" show (lookup item shelf)

-- Either keeps a reason on the Left, where Maybe only says Nothing
checkOrder :: String -> Either String Int
checkOrder item = case lookup item shelf of
  Nothing -> Left (item ++ " has no shelf entry")
  Just n -> Right n

How it works

  1. lookup item shelf answers with Nothing on a missing key instead of crashing.
  2. fromMaybe 0 substitutes a default for Nothing, and maybe "not stocked" show runs a function over the Just on its way out.
  3. checkOrder cases on that same lookup, yielding Left (item ++ " has no shelf entry") or Right n.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
697
Tokens
103
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 88 seconds.

Type this snippet

Step 3 of 3 in Types & records, step 18 of 27 in Language basics.

← Previous Next →