Source file accessor_either.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
open! Base
open! Import

type ('f, 's) t = ('f, 's) Either.t =
  | First of 'f
  | Second of 's
[@@deriving accessors]

let swapped = [%accessor Accessor.isomorphism ~get:Either.swap ~construct:Either.swap]

let assocl = function
  | First a -> First (First a)
  | Second (First a) -> First (Second a)
  | Second (Second a) -> Second a

and assocr = function
  | First (First a) -> First a
  | First (Second a) -> Second (First a)
  | Second a -> Second (Second a)
;;

let assocl = [%accessor Accessor.isomorphism ~get:assocl ~construct:assocr]
and assocr = [%accessor Accessor.isomorphism ~get:assocr ~construct:assocl]

module Index = struct
  type t =
    | First
    | Second
  [@@deriving accessors, compare, hash, sexp_of]
end

let tuple =
  [%accessor
    Accessor.isomorphism
      ~get:(function
        | First a -> Index.First, a
        | Second a -> Second, a)
      ~construct:(function
        | Index.First, a -> First a
        | Second, a -> Second a)]
;;

let each = [%accessor tuple @> Accessor_tuple2.snd]
let eachi = [%accessor tuple @> Accessor_tuple2.sndi]

module First = Accessor.Of_monad2 (struct
    include Either.First

    let apply = `Custom apply
  end)

module Second = Accessor.Of_monad2 (struct
    include Either.Second

    let apply = `Custom apply
  end)