diff --git a/CHANGES b/CHANGES index 554b25d62..c2b8188ce 100644 --- a/CHANGES +++ b/CHANGES @@ -9,6 +9,7 @@ * In the Lwt_io module, add `?cloexec:bool` optional arguments to functions that create file descriptors (`pipe`). The `?cloexec` argument is simply forwarded to the wrapped Lwt_unix function. (#872, #911, Antonin Décimo) * Add Lwt_result.error, Lwt_result.iter, and Lwt_result.iter_error for consistency with Stdlib. (#927, Antonin Décimo) + * Lwt_result.bind_error (#943, Boning Dong) ====== Misc ====== diff --git a/src/core/lwt_result.ml b/src/core/lwt_result.ml index 98c327b93..af83426d0 100644 --- a/src/core/lwt_result.ml +++ b/src/core/lwt_result.ml @@ -53,7 +53,13 @@ let bind e f = (function | Error e -> Lwt.return (Error e) | Ok x -> f x) - + +let bind_error e f = + Lwt.bind e + (function + | Error e -> f e + | Ok x -> Lwt.return (Ok x)) + let bind_lwt e f = Lwt.bind e (function diff --git a/src/core/lwt_result.mli b/src/core/lwt_result.mli index 5792e9d5b..b2df2328a 100644 --- a/src/core/lwt_result.mli +++ b/src/core/lwt_result.mli @@ -39,6 +39,9 @@ val map_error : ('e1 -> 'e2) -> ('a,'e1) t -> ('a,'e2) t val bind : ('a,'e) t -> ('a -> ('b,'e) t) -> ('b,'e) t +val bind_error : ('a,'e1) t -> ('e1 -> ('a,'e2) t) -> ('a,'e2) t +(** @since 5.6.0 *) + val bind_lwt : ('a,'e) t -> ('a -> 'b Lwt.t) -> ('b,'e) t val bind_lwt_error : ('a,'e1) t -> ('e1 -> 'e2 Lwt.t) -> ('a,'e2) t diff --git a/test/core/test_lwt_result.ml b/test/core/test_lwt_result.ml index a111bf9bb..e1fc3f775 100644 --- a/test/core/test_lwt_result.ml +++ b/test/core/test_lwt_result.ml @@ -65,7 +65,22 @@ let suite = let actual = Lwt_result.bind x (fun y -> Lwt_result.return (y + 1)) in Lwt.return (actual = x) ); + + test "bind_error" + (fun () -> + let x = Lwt_result.return 0 in + let actual = Lwt_result.bind_error x (fun y -> Lwt_result.return (y + 1)) in + Lwt.return (actual = x) + ); + test "bind_error, error case" + (fun () -> + let x = Lwt_result.fail 0 in + let correct = Lwt_result.return 1 in + let actual = Lwt_result.bind_error x (fun y -> Lwt_result.return (y + 1)) in + Lwt.return (actual = correct) + ); + test "ok" (fun () -> let x = Lwt.return 0 in