diff --git a/core/CCOpt.ml b/core/CCOpt.ml index a1dd5395..cc087ca2 100644 --- a/core/CCOpt.ml +++ b/core/CCOpt.ml @@ -110,7 +110,15 @@ let sequence_l l = 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 | None -> [] diff --git a/core/CCOpt.mli b/core/CCOpt.mli index e067a097..cd783f77 100644 --- a/core/CCOpt.mli +++ b/core/CCOpt.mli @@ -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 one [None], the result is [None]. *) -val guard : ('a -> 'b) -> 'a -> 'b option -(** [guard f x] calls [f x] and returns [Some y] if [f x = y]. If [f x] raises +val wrap : ?handler:(exn -> bool) -> ('a -> 'b) -> 'a -> 'b option +(** [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 - 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} *)