diff options
-rw-r--r-- | CHANGELOG.md | 2 | ||||
-rw-r--r-- | src/gleam/result.gleam | 18 | ||||
-rw-r--r-- | test/gleam/result_test.gleam | 10 |
3 files changed, 29 insertions, 1 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 84c732d..980f349 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ - The `int` module gains the `sum` and `product` functions. - The `float` module gains the `sum` and `product` functions. -- The `result` module gains the `lazy_or` function. +- The `result` module gains the `lazy_or` and `lazy_unwrap` functions. ## v0.12.0 - 2020-11-04 diff --git a/src/gleam/result.gleam b/src/gleam/result.gleam index 76ee0e1..c381cae 100644 --- a/src/gleam/result.gleam +++ b/src/gleam/result.gleam @@ -165,6 +165,24 @@ pub fn unwrap(result: Result(a, e), or default: a) -> a { } } +/// Extract the Ok value from a result, evaluating the default function if the result +/// is an Error. +/// +/// ## Examples +/// +/// > unwrap(Ok(1), fn() { 0 }) +/// 1 +/// +/// > unwrap(Error(""), fn() { 0 }) +/// 0 +/// +pub fn lazy_unwrap(result: Result(a, e), or default: fn() -> a) -> a { + case result { + Ok(v) -> v + Error(_) -> default() + } +} + /// Transforms any error into Error(Nil) /// /// ## Examples diff --git a/test/gleam/result_test.gleam b/test/gleam/result_test.gleam index d047496..d7b6048 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 lazy_unwrap_test() { + Ok(1) + |> result.lazy_unwrap(fn() { 50 }) + |> should.equal(1) + + Error("nope") + |> result.lazy_unwrap(fn() { 50 }) + |> should.equal(50) +} + pub fn nil_error_test() { Error("error_string") |> result.nil_error |