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
lookup item shelfrespondeNothingante una clave ausente en vez de reventar.fromMaybe 0cambiaNothingpor un valor por defecto, ymaybe "not stocked" showaplica una función alJust.checkOrderhace un case sobre esa misma búsqueda y produceLeft (item ++ " has no shelf entry")oRight n.
Palabras clave y builtins usados aquí
EitherIntJustLeftNothingRightStringcaseimportmoduleofwhere
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.
Paso 3 de 3 en Tipos y registros; paso 18 de 27 en Fundamentos del lenguaje.