typestar

Maybe y Either en Haskell

Maybe reporta un valor ausente como Nothing; Either lleva un motivo en el 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

Cómo funciona

  1. lookup item shelf responde Nothing ante una clave ausente en vez de reventar.
  2. fromMaybe 0 cambia Nothing por un valor por defecto, y maybe "not stocked" show aplica una función al Just.
  3. checkOrder hace un case sobre esa misma búsqueda y produce Left (item ++ " has no shelf entry") o Right n.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
697
Tokens
103
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 88 segundos.

Escribe este fragmento

Paso 3 de 3 en Tipos y registros; paso 18 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →