diff options
author | Giacomo Cavalieri <giacomo.cavalieri@icloud.com> | 2023-06-04 22:22:03 +0200 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2023-06-14 17:26:33 +0100 |
commit | b8dc3d2df625f7fa8fe6963e58ded088db3170ab (patch) | |
tree | f1ec0729034473827d90ec7cfa57d5eb44ba080e /src | |
parent | cae360dea442e43d2a9770358ca607d04b7f7efe (diff) | |
download | gleam_stdlib-b8dc3d2df625f7fa8fe6963e58ded088db3170ab.tar.gz gleam_stdlib-b8dc3d2df625f7fa8fe6963e58ded088db3170ab.zip |
Add `result.recover`
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/result.gleam | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/gleam/result.gleam b/src/gleam/result.gleam index 3833add..5207a66 100644 --- a/src/gleam/result.gleam +++ b/src/gleam/result.gleam @@ -444,3 +444,40 @@ pub fn replace_error(result: Result(a, e1), error: e2) -> Result(a, e2) { pub fn values(results: List(Result(a, e))) -> List(a) { list.filter_map(results, fn(r) { r }) } + +/// Updates a value held within the `Error` of a result by calling a given function +/// on it, where the given function also returns a result. The two results are +/// then merged together into one result. +/// +/// If the result is an `Ok` rather than `Error` the function is not called and the +/// result stays the same. +/// +/// This function is useful for chaining together computations that may fail +/// and trying to recover from possible errors. +/// +/// ## Examples +/// +/// ```gleam +/// > Ok(1) |> recover(with: fn(_) { Error("failed to recover") }) +/// Ok(1) +/// ``` +/// +/// ```gleam +/// > Error(1) |> recover(with: fn(error) { Ok(error + 1) }) +/// Ok(2) +/// ``` +/// +/// ```gleam +/// > Error(1) |> recover(with: fn(error) { Error("failed to recover") }) +/// Error("failed to recover") +/// ``` +/// +pub fn recover( + result: Result(a, e), + with fun: fn(e) -> Result(a, f), +) -> Result(a, f) { + case result { + Ok(value) -> Ok(value) + Error(error) -> fun(error) + } +} |