diff options
-rw-r--r-- | src/gleam/result.gleam | 22 | ||||
-rw-r--r-- | test/gleam/result_test.gleam | 10 |
2 files changed, 32 insertions, 0 deletions
diff --git a/src/gleam/result.gleam b/src/gleam/result.gleam index 5d77408..9f419b5 100644 --- a/src/gleam/result.gleam +++ b/src/gleam/result.gleam @@ -202,6 +202,28 @@ pub fn unwrap_error(result: Result(a, e), or default: e) -> e { } } +/// Extracts the inner value from a result. Both the value and error must be of +/// the same type. +/// +/// ## Examples +/// +/// ```gleam +/// > unwrap_both(Error(1)) +/// 1 +/// ``` +/// +/// ```gleam +/// > unwrap_both(Ok(2)) +/// 2 +/// ``` +/// +pub fn unwrap_both(result: Result(a, a)) -> a { + case result { + Ok(a) -> a + Error(a) -> a + } +} + /// Transforms any error into `Error(Nil)`. /// /// ## Examples diff --git a/test/gleam/result_test.gleam b/test/gleam/result_test.gleam index 79f1d6c..c580950 100644 --- a/test/gleam/result_test.gleam +++ b/test/gleam/result_test.gleam @@ -97,6 +97,16 @@ pub fn unwrap_error_test() { |> should.equal(50) } +pub fn unwrap_both_test() { + Error(1) + |> result.unwrap_both + |> should.equal(1) + + Ok("yup") + |> result.unwrap_both + |> should.equal("yup") +} + pub fn lazy_unwrap_test() { Ok(1) |> result.lazy_unwrap(fn() { 50 }) |