Legend:
Library
Module
Module type
Parameter
Class
Class type
Result: Handling results of operations which can fail
Overview
Operations returning a result type can be used to have some functional exception handling.
Let's say that you have some operatios returning a result object.
let op1 ... : (int, error) result = ...
let op2 ... : (char, error) result = ...
let op3 ... : (string, error) result = ...
let op3 ... : (t, error) result = ...
You can chain these operations by concentrating on the success case only and handling the error case at the end of the chain.
match
let* i = op1 ... in
let* c = op2 ... i ... in
let* s = op3 ... i ... c ... in
op4 ... i ... c ... s
with
| Ok x ->
(* Handling of the success case *)
| Error e ->
(* Handling of the error case which might have
occurred in any of the steps *)
A simple example:
type 'a r = ('a, string) result
let add (a: int r) (b: int r): int r =
let* x = a in
let* y = b in
Ok (x + y)
let divide (a: int r) (b: int r): int r =
let* x = a in
let* y = b in
if y = 0 then
Error "Division by Zero"
else
Ok (x / y)
assert (
add (Ok 1) (divide (Ok 2) (Ok 0))
=
Error "Division by Zero"
)
assert (
add (Ok 1) (divide (Ok 10) (Ok 2))
=
Ok 6
)
'a is the result type in case of success and 'e' is the result type in case of failure. It is implemented by the ocaml type result from the ocaml standard library.