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
lookup item shelfanswers withNothingon a missing key instead of crashing.fromMaybe 0substitutes a default forNothing, andmaybe "not stocked" showruns a function over theJuston its way out.checkOrdercases on that same lookup, yieldingLeft (item ++ " has no shelf entry")orRight n.
Keywords and builtins used here
EitherIntJustLeftNothingRightStringcasecheckOrderfromMaybeimportmoduleofonHandreportshelfwhere
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.
Step 3 of 3 in Types & records, step 18 of 27 in Language basics.