Source

spotlib / lib / result.ml

The default branch has multiple heads

Full commit
type ('a, 'error) t = [`Ok of 'a | `Error of 'error]

include Monad.Make2(struct
  type ('a, 'error) t = [`Ok of 'a | `Error of 'error]

  let return v = `Ok v

  let bind t f = match t with
    | `Ok v -> f v
    | `Error e -> `Error e
end)

let fail e = `Error e

let catch f = 
  let module Error = struct exception Error end in
  let error = ref None in
  let fail e = error := Some e; raise Error.Error in
  try `Ok (f ~fail) with
  | Error.Error -> 
      match !error with
      | Some e -> `Error e
      | None -> assert false

let catch_exn f = catch (fun ~fail -> try f () with e -> fail e)
  
module Pervasives = struct

  let ok x = `Ok x
  let ng x = `Error x

  let from_Ok to_exn = function
    | `Ok v -> v
    | `Error e -> raise (to_exn e)
  
  let result left right = function
    | `Ok v -> left v
    | `Error e -> right e

end

include Pervasives