Chain together many computations that may not return a value.
It is helpful to see its definition:
let flatMap t ~f =
match t with
| Some x -> f x
| None -> None
This means we only continue with the callback if we have a value.
For example, say you need to parse some user input as a month:
let toValidMonth (month: int) : (int option) =
if (1 <= month && month <= 12) then
Some month
else
None
in
let userInput = "5" in
Int.ofString userInput
|> Option.flatMap ~f:toValidMonth
If String.toInt
produces None
(because the userInput
was not an integer) this entire chain of operations will short-circuit and result in None
. If toValidMonth
results in None
, again the chain of computations will result in None
.
See Infix.(>>=)
for an operator version of this function.
Examples
Option.flatMap (Some [1, 2, 3]) ~f:List.head = Some 1
Option.flatMap (Some []) ~f:List.head = None