rename CCOpt.guard into CCOpt.wrap, add an optional handler, add CCOpt.wrap2

This commit is contained in:
Simon Cruanes 2014-08-08 20:06:44 +02:00
parent 579a135829
commit edfadba1ef
2 changed files with 17 additions and 4 deletions

View file

@ -110,7 +110,15 @@ let sequence_l l =
sequence_l [] = Some [] sequence_l [] = Some []
*) *)
let guard f x = try Some (f x) with Not_found -> None let wrap ?(handler=fun _ -> true) f x =
try Some (f x)
with e ->
if handler e then None else raise e
let wrap2 ?(handler=fun _ -> true) f x y =
try Some (f x y)
with e ->
if handler e then None else raise e
let to_list o = match o with let to_list o = match o with
| None -> [] | None -> []

View file

@ -69,10 +69,15 @@ val sequence_l : 'a t list -> 'a list t
every [xi] is [Some yi]. Otherwise, if the list contains at least every [xi] is [Some yi]. Otherwise, if the list contains at least
one [None], the result is [None]. *) one [None], the result is [None]. *)
val guard : ('a -> 'b) -> 'a -> 'b option val wrap : ?handler:(exn -> bool) -> ('a -> 'b) -> 'a -> 'b option
(** [guard f x] calls [f x] and returns [Some y] if [f x = y]. If [f x] raises (** [wrap f x] calls [f x] and returns [Some y] if [f x = y]. If [f x] raises
any exception, the result is [None]. This can be useful to wrap functions any exception, the result is [None]. This can be useful to wrap functions
such as [Map.S.find]. *) such as [Map.S.find].
@param handler the exception handler, which returns [true] if the
exception is to be caught. *)
val wrap2 : ?handler:(exn -> bool) -> ('a -> 'b -> 'c) -> 'a -> 'b -> 'c option
(** [wrap2 f x y] is similar to {!wrap1} but for binary functions. *)
(** {2 Applicative} *) (** {2 Applicative} *)