From 577697a91a68dab115212127267b65b340aee6d6 Mon Sep 17 00:00:00 2001 From: Gavin McGimpsey Date: Mon, 16 Oct 2023 22:57:05 -0700 Subject: 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. --- src/gleam/result.gleam | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) (limited to 'src') 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), -- cgit v1.2.3