Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bind_error to Lwt_result #943

Merged
merged 5 commits into from
Jun 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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 ======

Expand Down
8 changes: 7 additions & 1 deletion src/core/lwt_result.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/core/lwt_result.mli
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions test/core/test_lwt_result.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down