From 4e79b72306e1cb9018b2c7a1cfa4d72eb133be79 Mon Sep 17 00:00:00 2001 From: Ewen Maclean Date: Tue, 25 Jan 2022 20:05:11 +0000 Subject: [PATCH] adding opt_map to simplify result function application over optionals (#397) adding `Result.opt_map` to simplify result function application over optionals --- src/core/CCResult.ml | 8 ++++++++ src/core/CCResult.mli | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/src/core/CCResult.ml b/src/core/CCResult.ml index 31c9f3e51..90e6159da 100644 --- a/src/core/CCResult.ml +++ b/src/core/CCResult.ml @@ -68,6 +68,14 @@ let of_exn_trace e = in Error res +let opt_map f e = match e with + | None -> Ok None + | Some x -> + begin match f x with + | Ok x -> Ok (Some x) + | Error e -> Error e + end + let map f e = match e with | Ok x -> Ok (f x) | Error s -> Error s diff --git a/src/core/CCResult.mli b/src/core/CCResult.mli index 042131724..78f21ef8f 100644 --- a/src/core/CCResult.mli +++ b/src/core/CCResult.mli @@ -63,6 +63,10 @@ val add_ctxf : ('a, Format.formatter, unit, ('b, string) t -> ('b, string) t) fo ]} @since 1.2 *) +val opt_map : ('a -> ('b, 'c) t) -> 'a option -> ('b option, 'c) t +(** Map a fallible operation through an option. + @since NEXT_RELEASE *) + val map : ('a -> 'b) -> ('a, 'err) t -> ('b, 'err) t (** Map on success. *)