Result
is often used to handle error messages.
#
| Ok of 'ok
| |||
#
| Error of 'err
|
'a
is a function's expected return type, and 'b
is often an error message string.
let ric_of_ticker = function
| "IBM" -> Ok "IBM.N"
| "MSFT" -> Ok "MSFT.OQ"
| "AA" -> Ok "AA.N"
| "CSCO" -> Ok "CSCO.OQ"
| _ as ticker -> Error (sprintf "can't find ric of %s" ticker)
The return type of ric_of_ticker could be string option
, but (string, string)
Result.t
gives more control over the error message.
e.g. failf "Couldn't find bloogle %s" (Bloogle.to_string b)
ok_fst
is useful with List.partition_map
. Continuing the above example:
let rics, errors = List.partition_map ~f:Result.ok_fst
(List.map ~f:ric_of_ticker ["AA"; "F"; "CSCO"; "AAPL"])