OCaml Results
An option says whether there is a value, but not why there isn't one. When the caller needs to know what went wrong, use the result type:
type ('a, 'e) result = Ok of 'a | Error of 'eOk v carries a successful value, Error e carries an error description. The error can be any type: a string, or better, your own variant.
let parse_age s =
match int_of_string_opt s with
| None -> Error ("not a number: " ^ s)
| Some n when n < 0 -> Error "age cannot be negative"
| Some n when n > 150 -> Error "age is unrealistically high"
| Some n -> Ok n
let () =
List.iter
(fun s ->
match parse_age s with
| Ok age -> Printf.printf "%S -> Ok %d\n" s age
| Error msg -> Printf.printf "%S -> Error: %s\n" s msg)
[ "34"; "-3"; "abc"; "200" ]"34" -> Ok 34
"-3" -> Error: age cannot be negative
"abc" -> Error: not a number: abc
"200" -> Error: age is unrealistically high
Typed errors
Strings are easy, but a variant of possible errors lets callers react to each case and lets the compiler check that all cases are handled:
type withdraw_error =
| Insufficient_funds of int (* how much is missing *)
| Account_frozen
| Invalid_amount
let withdraw ~balance ~frozen amount =
if amount <= 0 then Error Invalid_amount
else if frozen then Error Account_frozen
else if amount > balance then Error (Insufficient_funds (amount - balance))
else Ok (balance - amount)
let explain = function
| Insufficient_funds n -> Printf.sprintf "you need %d more" n
| Account_frozen -> "the account is frozen"
| Invalid_amount -> "the amount must be positive"
let () =
[ (100, false, 30); (100, false, 130); (100, true, 10); (100, false, 0) ]
|> List.iter (fun (balance, frozen, amount) ->
match withdraw ~balance ~frozen amount with
| Ok left -> Printf.printf "withdrew %d, %d left\n" amount left
| Error e -> Printf.printf "refused: %s\n" (explain e))withdrew 30, 70 left
refused: you need 30 more
refused: the account is frozen
refused: the amount must be positive
The Result module
| Function | Meaning |
|---|---|
Result.map f r |
transform an Ok value |
Result.map_error f r |
transform an Error value |
Result.bind r f |
chain a step that returns a result |
Result.value r ~default |
the Ok value or a default |
Result.is_ok, Result.is_error |
test |
Result.to_option r |
drop the error information |
Chaining with let*
As with options, a binding operator turns a chain of fallible steps into straight-line code. The first Error stops the chain:
let ( let* ) = Result.bind
let parse_int field s =
match int_of_string_opt (String.trim s) with
| Some n -> Ok n
| None -> Error (Printf.sprintf "field %s: %S is not a number" field s)
let check_positive field n = if n > 0 then Ok n else Error ("field " ^ field ^ " must be positive")
(* "width,height" -> area *)
let area_of_line line =
match String.split_on_char ',' line with
| [ w; h ] ->
let* width = parse_int "width" w in
let* height = parse_int "height" h in
let* width = check_positive "width" width in
let* height = check_positive "height" height in
Ok (width * height)
| _ -> Error "expected two comma-separated values"
let () =
[ "4,5"; "4, x"; "0,3"; "1,2,3" ]
|> List.iter (fun line ->
match area_of_line line with
| Ok a -> Printf.printf "%-6s area %d\n" line a
| Error e -> Printf.printf "%-6s error: %s\n" line e)4,5 area 20
4, x error: field height: " x" is not a number
0,3 error: field width must be positive
1,2,3 error: expected two comma-separated values
Collecting results
To process a whole list and stop at the first error, fold with Result.bind:
let parse s = match int_of_string_opt s with Some n -> Ok n | None -> Error s
let parse_all strings =
List.fold_right
(fun s acc -> Result.bind acc (fun rest -> Result.map (fun n -> n :: rest) (parse s)))
strings (Ok [])
let show = function
| Ok nums -> "Ok [" ^ String.concat "; " (List.map string_of_int nums) ^ "]"
| Error bad -> "Error: could not parse " ^ bad
let () =
print_endline (show (parse_all [ "1"; "2"; "3" ]));
print_endline (show (parse_all [ "1"; "two"; "3" ]))Ok [1; 2; 3]
Error: could not parse two
Options, results or exceptions?
| Use | When |
|---|---|
option |
absence is normal and needs no explanation (lookup, search) |
result |
failure is expected and the caller needs the reason (parsing, validation) |
| exception | truly exceptional or programming errors (index out of bounds, invariants) |
Test yourself
What are the two constructors of result?
SomeandNoneOkandErrorSuccessandFailureLeftandRight
When should you prefer result over option?
- When there is no value
- When the caller needs to know why the operation failed
- Never
- For loops
In a chain of let* steps using Result.bind, what happens at the first Error?
- It is ignored
- The remaining steps are skipped and that Error is the result
- An exception is raised
- The chain restarts