diff options
author | Louis Pilfold <louis@lpil.uk> | 2022-02-22 17:44:27 +0000 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2022-02-22 17:44:27 +0000 |
commit | ab21b63529e9d81d3855207b4cd7be0631278acb (patch) | |
tree | 88e08ee98b39fbaf860a0985e737bf7f81a58cdf | |
parent | abb7b73fddb3d2ebbd1b1ba30d40459704f6fdab (diff) | |
download | gleam_stdlib-ab21b63529e9d81d3855207b4cd7be0631278acb.tar.gz gleam_stdlib-ab21b63529e9d81d3855207b4cd7be0631278acb.zip |
result.unwrap_error
-rw-r--r-- | src/gleam/result.gleam | 46 | ||||
-rw-r--r-- | test/gleam/result_test.gleam | 10 |
2 files changed, 48 insertions, 8 deletions
diff --git a/src/gleam/result.gleam b/src/gleam/result.gleam index c774219..5d77408 100644 --- a/src/gleam/result.gleam +++ b/src/gleam/result.gleam @@ -141,11 +141,15 @@ pub fn then( /// /// ## Examples /// -/// > unwrap(Ok(1), 0) -/// 1 +/// ```gleam +/// > unwrap(Ok(1), 0) +/// 1 +/// ``` /// -/// > unwrap(Error(""), 0) -/// 0 +/// ```gleam +/// > unwrap(Error(""), 0) +/// 0 +/// ``` /// pub fn unwrap(result: Result(a, e), or default: a) -> a { case result { @@ -159,11 +163,15 @@ pub fn unwrap(result: Result(a, e), or default: a) -> a { /// /// ## Examples /// -/// > lazy_unwrap(Ok(1), fn() { 0 }) -/// 1 +/// ```gleam +/// > lazy_unwrap(Ok(1), fn() { 0 }) +/// 1 +/// ``` /// -/// > lazy_unwrap(Error(""), fn() { 0 }) -/// 0 +/// ```gleam +/// > lazy_unwrap(Error(""), fn() { 0 }) +/// 0 +/// ``` /// pub fn lazy_unwrap(result: Result(a, e), or default: fn() -> a) -> a { case result { @@ -172,6 +180,28 @@ pub fn lazy_unwrap(result: Result(a, e), or default: fn() -> a) -> a { } } +/// Extracts the `Error` value from a result, returning a default value if the result +/// is an `Ok`. +/// +/// ## Examples +/// +/// ```gleam +/// > unwrap_error(Error(1), 0) +/// 1 +/// ``` +/// +/// ```gleam +/// > unwrap_error(Ok(""), 0) +/// 0 +/// ``` +/// +pub fn unwrap_error(result: Result(a, e), or default: e) -> e { + case result { + Ok(_) -> default + Error(e) -> e + } +} + /// Transforms any error into `Error(Nil)`. /// /// ## Examples diff --git a/test/gleam/result_test.gleam b/test/gleam/result_test.gleam index c34c7ed..79f1d6c 100644 --- a/test/gleam/result_test.gleam +++ b/test/gleam/result_test.gleam @@ -87,6 +87,16 @@ pub fn unwrap_test() { |> should.equal(50) } +pub fn unwrap_error_test() { + Error(1) + |> result.unwrap_error(50) + |> should.equal(1) + + Ok("nope") + |> result.unwrap_error(50) + |> should.equal(50) +} + pub fn lazy_unwrap_test() { Ok(1) |> result.lazy_unwrap(fn() { 50 }) |