package fmlib

  1. Overview
  2. Docs
Functional monadic library

Install

Dune Dependency

Authors

Maintainers

Sources

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

doc/src/fmlib.fmlib_std/result.ml.html

Source file result.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
type ('a,'e) t = ('a,'e) result


let return (a: 'a): ('a,'e) t =
    Ok a


let (>>=) (m: ('a,'e) t) (f: 'a -> ('b,'e) t): ('b,'e) t =
    match m with
    | Ok a ->
        f a
    | Error e ->
        Error e

let ( let* ) = (>>=)



module Monad (E: Interfaces.ANY) =
struct
    type 'a t = ('a, E.t) result

    let return = return

    let (>>=)  = (>>=)

    let ( let* ) = (>>=)
end



(* Unit tests *)
(*****************************************)

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)

let%test _ =
    add (Ok 1) (divide (Ok 2) (Ok 0))
    =
    Error "Division by Zero"

let%test _ =
    add (Ok 1) (divide (Ok 10) (Ok 2))
    =
    Ok 6
OCaml

Innovation. Community. Security.