From f10d979432ea5c4d946586a01f11d19a7e08886f Mon Sep 17 00:00:00 2001 From: Vincent Bernardoff Date: Fri, 15 Dec 2017 17:00:50 +0100 Subject: [PATCH] Stdlib: add Option.try_with --- lib_stdlib/option.ml | 2 ++ lib_stdlib/option.mli | 2 ++ 2 files changed, 4 insertions(+) diff --git a/lib_stdlib/option.ml b/lib_stdlib/option.ml index d89c3d71d..3e0b5e76c 100644 --- a/lib_stdlib/option.ml +++ b/lib_stdlib/option.ml @@ -32,3 +32,5 @@ let first_some a b = match a, b with | None, Some v -> Some v | Some v, _ -> Some v +let try_with f = + try Some (f ()) with _ -> None diff --git a/lib_stdlib/option.mli b/lib_stdlib/option.mli index bd4b32f81..c14400fb9 100644 --- a/lib_stdlib/option.mli +++ b/lib_stdlib/option.mli @@ -25,3 +25,5 @@ val unopt_map: f:('a -> 'b) -> default:'b -> 'a option -> 'b (** First input of form [Some x], or [None] if none **) val first_some: 'a option -> 'a option -> 'a option +(** [Some (f ())] if [f] does not raise, [None] otherwise *) +val try_with : (unit -> 'a) -> 'a option