diff options
author | Sebastian <s@porto5.com> | 2020-10-14 16:05:24 +1100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2020-10-17 13:33:20 +0200 |
commit | 1489e38aaa076112fe580cd096e4c827304d2bd3 (patch) | |
tree | f9b81627920250a85033ead47a583af13898bebf | |
parent | 42c75c7c9594a068d72b75390b2a47e17544d087 (diff) | |
download | gleam_stdlib-1489e38aaa076112fe580cd096e4c827304d2bd3.tar.gz gleam_stdlib-1489e38aaa076112fe580cd096e4c827304d2bd3.zip |
Add result.all
-rw-r--r-- | CHANGELOG.md | 1 | ||||
-rw-r--r-- | src/gleam/result.gleam | 16 | ||||
-rw-r--r-- | test/gleam/result_test.gleam | 10 |
3 files changed, 27 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index e920741..e3c67f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - The `list` module gains the `each`, and `partition` functions. - The `int` and `float` modules gain the `negate` function. +- The `result` module gains the `all` function. ## v0.11.0 - 2020-08-22 diff --git a/src/gleam/result.gleam b/src/gleam/result.gleam index 88f933a..2ebf2ef 100644 --- a/src/gleam/result.gleam +++ b/src/gleam/result.gleam @@ -1,3 +1,5 @@ +import gleam/list + /// Result represents the result of something that may succeed or not. /// `Ok` means it was successful, `Error` means it was not successful. /// @@ -199,3 +201,17 @@ pub fn or(first: Result(a, e), second: Result(a, e)) -> Result(a, e) { Error(_) -> second } } + +/// Combine a list of results into a single result. +/// If all elements in the list are Ok then returns an Ok holding the list of values. +/// If any element is Error then returns the first error. +/// +/// ## Examples +/// > all([Ok(1), Ok(2)]) +/// Ok([1, 2]) +/// +/// > all([Ok(1), Error("e")]) +/// Error("e") +pub fn all(results: List(Result(a, e))) -> Result(List(a), e) { + list.try_map(results, fn(x) { x }) +} diff --git a/test/gleam/result_test.gleam b/test/gleam/result_test.gleam index 4abc983..1c585b5 100644 --- a/test/gleam/result_test.gleam +++ b/test/gleam/result_test.gleam @@ -118,3 +118,13 @@ pub fn or_test() { |> result.or(Error("Error 2")) |> should.equal(Error("Error 2")) } + +pub fn all_test() { + [Ok(1), Ok(2), Ok(3)] + |> result.all + |> should.equal(Ok([1, 2, 3])) + + [Ok(1), Error("a"), Error("b"), Ok(3)] + |> result.all + |> should.equal(Error("a")) +} |