Module Support.Either

Ad hoc disjoint unions of two types.

include module type of Stdlib.Either
type (!'a, !'b) t = ('a, 'b) Stdlib__Either.t =
  1. | Left of 'a
  2. | Right of 'b
val left : 'a -> ('a, 'b) t
val right : 'b -> ('a, 'b) t
val is_left : ('a, 'b) t -> bool
val is_right : ('a, 'b) t -> bool
val find_left : ('a, 'b) t -> 'a option
val find_right : ('a, 'b) t -> 'b option
val map_left : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t
val map_right : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t
val map : left:('a1 -> 'a2) -> right:('b1 -> 'b2) -> ('a1, 'b1) t -> ('a2, 'b2) t
val fold : left:('a -> 'c) -> right:('b -> 'c) -> ('a, 'b) t -> 'c
val iter : left:('a -> unit) -> right:('b -> unit) -> ('a, 'b) t -> unit
val for_all : left:('a -> bool) -> right:('b -> bool) -> ('a, 'b) t -> bool
val equal : left:('a -> 'a -> bool) -> right:('b -> 'b -> bool) -> ('a, 'b) t -> ('a, 'b) t -> bool
val compare : left:('a -> 'a -> int) -> right:('b -> 'b -> int) -> ('a, 'b) t -> ('a, 'b) t -> int
val eliminate : ('e -> 'c) -> ('a -> 'c) -> ('e, 'a) t -> 'c

Eliminator for disjoint unions.

val bimap : ('e1 -> 'e2) -> ('a -> 'b) -> ('e1, 'a) t -> ('e2, 'b) t

Transforms both sides of the union.

val void_right : ('e, 'a) t -> ('e, unit) t

Forgets the right-hand side of the union.

val void_left : ('e, 'a) t -> (unit, 'a) t

Forgets the left-hand side of the union.

val void : ('e, 'a) t -> (unit, unit) t

Forgets both sides of the union.

val bind : ('a -> ('e, 'b) t) -> ('e, 'a) t -> ('e, 'b) t

Promotes a function that constructs a union into a function that transforms a union.

Either.bind and Either.right witness that Either.t is a monad if the left-hand type is fixed.

val forget : ('e, 'a) t -> 'a option

Eliminates the union into a Stdlib.option, forgetting the value in the left-hand side.

val of_option : 'a option -> (unit, 'a) t

Converts a Stdlib.option into a union with a unit left-hand side.

val of_option' : (unit -> 'e) -> 'a option -> ('e, 'a) t

Converts a Stdlib.option into a union with a left-hand side constructed from a thunk in case the Stdlib.option contained Option.t.None.

val to_option : ('e, 'a) t -> 'a option

Converts a union into an option, forgetting the left side, if any.

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

Infix form of Either.bind.

val ($>) : ('e, 'a) t -> ('a -> 'b) -> ('e, 'b) t

Infix form of Either.map_right.

val trap : (unit -> 'a) -> (exn, 'a) t

Traps exceptions thrown by evaluating a function into a union. You can delay handling the exceptions until the union is eliminated by using the following trick. Suppose e : (exn, a) t. Then,

  eliminate
    (fun ex ->
      try raise ex with
      | Whatever -> do_something_to_handle_Whatever)
    (fun x -> success x)

The benefit of using trap is that you can be selective about which code gets its exceptions caught.