package preface

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file freer_monad.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
open Preface_core.Fun.Infix

module Over (Type : Preface_specs.Types.T1) = struct
  type 'a f = 'a Type.t

  type _ t =
    | Return : 'a -> 'a t
    | Bind : 'b f * ('b -> 'a t) -> 'a t

  let perform f = Bind (f, fun a -> Return a)

  type ('a, 'b) handle = ('a -> 'b) -> 'a f -> 'b
  type 'a handler = { handler : 'b. ('b, 'a) handle }

  module To_monad (Monad : Preface_specs.Monad.CORE) = struct
    type ('a, 'b) handle = ('a -> 'b Monad.t) -> 'a f -> 'b Monad.t
    type 'a handler = { handler : 'b. ('b, 'a) handle }

    let run f =
      let rec loop_run = function
        | Return a -> Monad.return a
        | Bind (intermediate, continue) ->
          let k x = loop_run (continue x) in
          f.handler k intermediate
      in
      loop_run
    ;;
  end

  let run f =
    let rec loop_run = function
      | Return a -> a
      | Bind (intermediate, continue) ->
        let k x = loop_run (continue x) in
        f.handler k intermediate
    in
    loop_run
  ;;

  let rec map f = function
    | Return x -> Return (f x)
    | Bind (i, c) -> Bind (i, c %> map f)
  ;;

  module Functor = Functor.Via_map (struct
    type nonrec 'a t = 'a t

    let map = map
  end)

  module Applicative = Applicative.Via_pure_and_apply (struct
    type nonrec 'a t = 'a t

    let pure a = Return a

    let rec apply f a =
      match f with
      | Return f' -> map f' a
      | Bind (i, c) -> Bind (i, c %> fun f -> apply f a)
    ;;
  end)

  module Monad = Monad.Via_return_and_bind (struct
    type nonrec 'a t = 'a t

    let return a = Return a

    let rec bind f = function
      | Return a -> f a
      | Bind (i, c) -> Bind (i, c %> bind f)
    ;;
  end)

  module Selective =
    Selective.Over_applicative_via_select
      (Applicative)
      (Selective.Select_from_monad (Monad))

  include (Monad : Preface_specs.MONAD with type 'a t := 'a t)
end
OCaml

Innovation. Community. Security.