Data.Maybe.fromJust
è stato menzionato da altre risposte già:
fromJust :: Maybe a -> a
fromJust Nothing = error "Maybe.fromJust: Nothing"
fromJust (Just x) = x
C'è anche maybe
(trovato in entrambi Prelude
e Data.Maybe
):
maybe :: b -> (a -> b) -> Maybe a -> b
maybe n _ Nothing = n
maybe _ f (Just x) = f x
fromJust
possono essere scritti utilizzando maybe
:
fromJust = maybe (error "Maybe.fromJust: Nothing") id
Come si può vedere, maybe
permette flessibilità nella gestione entrambi i casi senza la necessità di pattern matching:
\x -> maybe 0 (+ 2) x -- Nothing -> 0, Just 2 -> 4
Allo stesso modo, Prelude
e Data.Either
hanno either :: (a -> c) -> (b -> c) -> Either a b -> c
:
\x -> either (subtract 1) (* 2) x -- Left 5 -> 4, Right 3 -> 6
Se si definisce un data type
data MyDataType
= TypeA { foo :: Int, bar :: String }
| TypeB { foo :: Int, baz ::() }
| TypeC { bar :: String, baz ::() }
in questo modo, si finisce con le funzioni parziali per gli accessor.
foo :: MyDataType -> Int
bar :: MyDataType -> String
baz :: MyDataType ->()
Si chiamano funzioni parziali, al contrario di funzioni totali, perché solo i risultati per un sottoinsieme dei loro ingressi.
foo (TypeA { foo = 15, bar = "hello!" }) -- 15
bar (TypeB { foo = 12345679, baz =() }) -- error