diff options
author | Gavin McGimpsey <dev@gavinmcg.com> | 2023-10-16 22:57:05 -0700 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2023-10-19 10:37:49 +0100 |
commit | 577697a91a68dab115212127267b65b340aee6d6 (patch) | |
tree | eba5f4ae3e8ae104579cbb8e4fe26c22fbd374b9 /src | |
parent | a63339014ba5ebd5ad50b34bea53fb39d105ec52 (diff) | |
download | gleam_stdlib-577697a91a68dab115212127267b65b340aee6d6.tar.gz gleam_stdlib-577697a91a68dab115212127267b65b340aee6d6.zip |
Update result.gleam to clarify try and add examples of use
I found result.try confusing when I had not realized that it could "replace" an `Ok` with an `Error`. I also did not understand its use in function chaining because I hadn't seen an example of a function call creating the result that it takes as input. This changes the language to offer a more specific description of what result.try does, and to show examples of use that will hopefully demonstrate its value more clearly.
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/result.gleam | 19 |
1 files changed, 14 insertions, 5 deletions
diff --git a/src/gleam/result.gleam b/src/gleam/result.gleam index 5941f0e..8829cb0 100644 --- a/src/gleam/result.gleam +++ b/src/gleam/result.gleam @@ -124,12 +124,11 @@ pub fn flatten(result: Result(Result(a, e), e)) -> Result(a, e) { } } -/// Updates a value held within the `Ok` 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. +/// "Updates" an `Ok` result by passing its value to a function that yields a result, +/// and returning the yielded result. (This may "replace" the `Ok` with an `Error`.) /// -/// If the result is an `Error` rather than `Ok` the function is not called and the -/// result stays the same. +/// If the input is an `Error` rather than an `Ok`, the function is not called and +/// the original `Error` is returned. /// /// This function is the equivalent of calling `map` followed by `flatten`, and /// it is useful for chaining together multiple functions that may fail. @@ -147,6 +146,11 @@ pub fn flatten(result: Result(Result(a, e), e)) -> Result(a, e) { /// ``` /// /// ```gleam +/// > try(yield_ok_containing_1(), fn(x) { Ok(x + 1) }) +/// Ok(2) +/// ``` +/// +/// ```gleam /// > try(Ok(1), fn(_) { Error("Oh no") }) /// Error("Oh no") /// ``` @@ -156,6 +160,11 @@ pub fn flatten(result: Result(Result(a, e), e)) -> Result(a, e) { /// Error(Nil) /// ``` /// +/// ```gleam +/// > try(yield_deliberate_error(), fn(x) { Ok(x + 1) }) +/// Error(Deliberate) +/// ``` +/// pub fn try( result: Result(a, e), apply fun: fn(a) -> Result(b, e), |