This library fills a bunch of important niches in Elm. A Maybe can help
you with optional arguments, error handling, and records with optional fields.
Provide a default value, turning an optional value into a normal
value. This comes in handy when paired with functions like
Dict.get which gives back a Maybe.
withDefault 100 (Just 42) -- 42
withDefault 100 Nothing -- 100
withDefault "unknown" (Dict.get "Tom" Dict.empty) -- "unknown"Transform a Maybe value with a given function:
map sqrt (Just 9) == Just 3
map sqrt Nothing == NothingApply a function if all the arguments are Just a value.
map2 (+) (Just 3) (Just 4) == Just 7
map2 (+) (Just 3) Nothing == Nothing
map2 (+) Nothing (Just 4) == NothingChain together many computations that may fail. It is helpful to see its definition:
andThen : (a -> Maybe b) -> Maybe a -> Maybe b
andThen callback maybe =
case maybe of
Just value ->
callback value
Nothing ->
NothingThis means we only continue with the callback if things are going well. For
example, say you need to use (head : List Int -> Maybe Int) to get the
first month from a List and then make sure it is between 1 and 12:
toValidMonth : Int -> Maybe Int
toValidMonth month =
if month >= 1 && month <= 12 then
Just month
else
Nothing
getFirstMonth : List Int -> Maybe Int
getFirstMonth months =
head months
|> andThen toValidMonthIf head fails and results in Nothing (because the List was empty),
this entire chain of operations will short-circuit and result in Nothing.
If toValidMonth results in Nothing, again the chain of computations
will result in Nothing.
Represent values that may or may not exist. It can be useful if you have a record field that is only filled in sometimes. Or if a function takes a value sometimes, but does not absolutely need it.