package fmlib
- Overview
- No Docs
You can search for identifiers within the package.
in-package search v0.2.0
Install
Dune Dependency
Authors
Maintainers
Sources
sha256=0558665285e4d7691e5a80c90ab05a7acb86c09f03ceef6589f150f6d3574573
md5=fb61f4d6e7233cf8d1d71758e6110c1e
doc/fmlib.fmlib_std/Fmlib_std/Result/index.html
Module Fmlib_std.Result
Source
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
)
API
'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.
m >>= f
maps success result m
to f a
. In case of an error result f
is not called and the error remains.
let* a = m in f a
is the same as m >>= f
Monad
The result type encapsulated in a module which satisfies the monadic interface.