From d1a5e047fe7c290cd61afa02604273f9190ef715 Mon Sep 17 00:00:00 2001 From: Fardale Date: Fri, 24 Jan 2020 22:57:25 +0100 Subject: [PATCH] feat(CCResult): add get_lazy fixes #285 --- src/core/CCResult.ml | 9 +++++++++ src/core/CCResult.mli | 4 ++++ 2 files changed, 13 insertions(+) diff --git a/src/core/CCResult.ml b/src/core/CCResult.ml index 2b4dbd35..b30659b0 100644 --- a/src/core/CCResult.ml +++ b/src/core/CCResult.ml @@ -117,6 +117,15 @@ let get_or_failwith = function try ignore @@ get_or_failwith (Error "e"); false with Failure msg -> msg = "e" *) +let get_lazy default_fn x = match x with + | Ok x -> x + | Error e -> default_fn e + +(*$= get_lazy + (get_lazy (fun _ -> 2) (Ok 1)) (1) + (get_lazy (fun _ -> 2) (Error "error")) (2) +*) + let map_or f e ~default = match e with | Ok x -> f x | Error _ -> default diff --git a/src/core/CCResult.mli b/src/core/CCResult.mli index 1259ca26..e6b2cb30 100644 --- a/src/core/CCResult.mli +++ b/src/core/CCResult.mli @@ -101,6 +101,10 @@ val get_or_failwith : ('a, string) t -> 'a @raise Failure with [msg] if [e = Error msg]. @since 2.4 *) +val get_lazy : ('b -> 'a) -> ('a, 'b) t -> 'a +(** [get_lazy default_fn x] unwraps [x], but if [x = Error e] it returns [default_fr e] instead. + @since NEXT_RELEASE *) + val map_or : ('a -> 'b) -> ('a, 'c) t -> default:'b -> 'b (** [map_or f e ~default] returns [f x] if [e = Ok x], [default] otherwise. *)