Source

spotlib / lib / option.ml

The default branch has multiple heads

Full commit
type 'a t = 'a option

include Monad.Make(struct
  type 'a t = 'a option

  let return v = Some v

  let bind t f = match t with
    | Some v -> f v
    | None -> None
end)

let default v df = match v with
  | None -> df ()
  | Some v -> v

let catch f =
  let module Error = struct exception Error end in
  let fail () = raise Error.Error in
  try Some (f ~fail) with Error.Error -> None

let catch_exn f = catch (fun ~fail -> try f () with _ -> fail ())

let format f ppf = function
  | None -> Format.pp_print_string ppf "None"
  | Some v -> Format.fprintf ppf "Some (%a)" f v

module Pervasives = struct
  let from_Some = function
    | Some v -> v
    | _ -> invalid_arg "Option.from_Some"
        (* This should report the caller's location,
           but it is not possible...
        *)

  let (||=) v f = match v with
    | Some _ -> v
    | None -> f ()
end

include Pervasives