package fmlib

  1. Overview
  2. No Docs
Functional monadic library

Install

Dune Dependency

Authors

Maintainers

Sources

0.1.0.tar.gz
sha256=0558665285e4d7691e5a80c90ab05a7acb86c09f03ceef6589f150f6d3574573
md5=fb61f4d6e7233cf8d1d71758e6110c1e

doc/fmlib.fmlib_std/Fmlib_std/Result/index.html

Module Fmlib_std.ResultSource

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

Sourcetype ('a, 'e) t = ('a, 'e) result

'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.

Sourceval return : 'a -> ('a, 'e) t

return a is the same as Ok a.

Sourceval (>>=) : ('a, 'e) t -> ('a -> ('b, 'e) t) -> ('b, 'e) t

m >>= f

maps success result m to f a. In case of an error result f is not called and the error remains.

Sourceval (let*) : ('a, 'e) t -> ('a -> ('b, 'e) t) -> ('b, 'e) t

let* a = m in f a is the same as m >>= f

Monad

Sourcemodule Monad (E : Interfaces.ANY) : sig ... end

The result type encapsulated in a module which satisfies the monadic interface.

OCaml

Innovation. Community. Security.