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

Update result.gleam to clarify try and add examples of use #499

Merged
merged 2 commits into from
Oct 19, 2023
Merged
Changes from 1 commit
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
19 changes: 14 additions & 5 deletions src/gleam/result.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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")
/// ```
Expand All @@ -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),
Expand Down