`maybe` eliminates a `Maybe` value without writing a `Just`/`Nothing` match yourself. Its type is `b -> (a -> b) -> Maybe a -> b`: give it a default result, a handler for the contained value, and the `Maybe`. With `Nothing`, it returns the default; with `Just x`, it runs the handler on `x`. The handler can transform the value, while the default and handler result must have the same type. section 3.3.2
Table 3.1 Common functions used in conjunction with the Maybe type
|
Name
|
Type
|
Description
|
|---|---|---|
maybe
|
b -> (a -> b) -> Maybe a -> b
|
This function takes a default value, a function, and a
Maybe. If the
Maybe is
Nothing, the default value is being returned; otherwise, the function is being applied to the value in the
Just constructor and returns the result of that function call.
|
fromMaybe
|
a -> Maybe a -> a
|
This function takes a default value and a maybe as arguments. If the
Maybe is a
Nothing, the default value is returned; otherwise, the wrapped value from the
Just constructor is returned.
|
catMaybes
|
[Maybe a] -> [a]
|
This function takes a list of
Maybe values as an argument and returns a list of all unwrapped
Just values. All
Nothing values are ignored.
|
mapMaybe
|
(a -> Maybe b) -> [a] -> [b]
|
This function takes a function that receives a value and returns a
Maybe of potentially different type as its first argument and a list of values as its second. The returned list is a mapping of the function to the second argument, where all
Nothing results are simply discarded. Its definition is equivalent to
mapMaybe f xs = catMaybes (map f xs).
|
Compare `maybe` with related `Maybe` helpers: use `maybe` when the present value needs a function, and `fromMaybe` when it can be returned unchanged. section 3.3.2
Choose an IO action from an optional filename
After parsing command-line arguments, `maybe` can select the whole action to run. The default action prints usage help; the handler builds an action that prints the supplied filename. This works because actions are values too: the pure `maybe` expression decides which `IO ()` action the program performs. section 3.4
Format missing line numbers
For `[Maybe Int]`, `map (maybe "" show)` turns each present number into text and each missing number into an empty string. This is useful when optional data must become a uniform display value before padding and combining lines. section 4.3.4
Use `maybe` at the point where both cases should collapse into one result. It supports optional results such as parsed file paths and optional fields such as line numbers; it does not require treating `Nothing` as a crash or extracting a value that is not there. section 3.3.2 section 4.1.1
