diff options
-rw-r--r-- | CHANGELOG.md | 1 | ||||
-rw-r--r-- | src/gleam/result.gleam | 23 | ||||
-rw-r--r-- | test/gleam/result_test.gleam | 18 |
3 files changed, 42 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 913175d..8a6d071 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ - The `list.traverse` first argument gains the label `over`. - The `option` module gains the the `map`, `flatten`, `then` and `or` functions. +- The `result` module gains the the `or` function. ## 0.9.0 - 2020-05-26 diff --git a/src/gleam/result.gleam b/src/gleam/result.gleam index b686939..88f933a 100644 --- a/src/gleam/result.gleam +++ b/src/gleam/result.gleam @@ -176,3 +176,26 @@ pub fn unwrap(result: Result(a, e), or default: a) -> a { pub fn nil_error(result: Result(a, e)) -> Result(a, Nil) { map_error(result, fn(_) { Nil }) } + +/// Return the first value if it is Ok, otherwise return the second value. +/// +/// ## Examples +/// +/// > or(Ok(1), Ok(2)) +/// Ok(1) +/// +/// > or(Ok(1), Error("Error 2")) +/// Ok(1) +/// +/// > or(Error("Error 1"), Ok(2)) +/// Ok(2) +/// +/// > or(Error("Error 1"), Error("Error 2")) +/// Error("Error 2") +/// +pub fn or(first: Result(a, e), second: Result(a, e)) -> Result(a, e) { + case first { + Ok(_) -> first + Error(_) -> second + } +} diff --git a/test/gleam/result_test.gleam b/test/gleam/result_test.gleam index f6d7f6d..9bfbe66 100644 --- a/test/gleam/result_test.gleam +++ b/test/gleam/result_test.gleam @@ -100,3 +100,21 @@ pub fn nil_error_test() { |> result.nil_error |> should.equal(Ok(1)) } + +pub fn or_result_test() { + Ok(1) + |> result.or(Ok(2)) + |> should.equal(Ok(1)) + + Ok(1) + |> result.or(Error("Error 2")) + |> should.equal(Ok(1)) + + Error("Error 1") + |> result.or(Ok(2)) + |> should.equal(Ok(2)) + + Error("Error 1") + |> result.or(Error("Error 2")) + |> should.equal(Error("Error 2")) +} |