aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPeter Saxton <peterhsaxton@gmail.com>2020-12-02 16:42:37 +0000
committerLouis Pilfold <louis@lpil.uk>2020-12-02 17:28:03 +0000
commit334f11c5167402d43d0d7e52110e61ecba20ded0 (patch)
treeed9c66ffaf0176c27f87bc0a20b50b5acef8fc31
parente58fe7aeaf8b536706d2f6bbe9815cfdb2fc4fa9 (diff)
downloadgleam_stdlib-334f11c5167402d43d0d7e52110e61ecba20ded0.tar.gz
gleam_stdlib-334f11c5167402d43d0d7e52110e61ecba20ded0.zip
implement a lazy or function
-rw-r--r--src/gleam/result.gleam23
-rw-r--r--test/gleam/result_test.gleam18
2 files changed, 41 insertions, 0 deletions
diff --git a/src/gleam/result.gleam b/src/gleam/result.gleam
index 2ebf2ef..76ee0e1 100644
--- a/src/gleam/result.gleam
+++ b/src/gleam/result.gleam
@@ -202,6 +202,29 @@ pub fn or(first: Result(a, e), second: Result(a, e)) -> Result(a, e) {
}
}
+/// Return the first value if it is Ok, otherwise evaluates the given function for a fallback 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 lazy_or(first: Result(a, e), second: fn() -> Result(a, e)) -> Result(a, e) {
+ case first {
+ Ok(_) -> first
+ 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.
diff --git a/test/gleam/result_test.gleam b/test/gleam/result_test.gleam
index 1c585b5..d047496 100644
--- a/test/gleam/result_test.gleam
+++ b/test/gleam/result_test.gleam
@@ -119,6 +119,24 @@ pub fn or_test() {
|> should.equal(Error("Error 2"))
}
+pub fn lazy_or_test() {
+ Ok(1)
+ |> result.lazy_or(fn() { Ok(2)} )
+ |> should.equal(Ok(1))
+
+ Ok(1)
+ |> result.lazy_or(fn() { Error("Error 2")} )
+ |> should.equal(Ok(1))
+
+ Error("Error 1")
+ |> result.lazy_or(fn() { Ok(2)} )
+ |> should.equal(Ok(2))
+
+ Error("Error 1")
+ |> result.lazy_or(fn() { Error("Error 2")} )
+ |> should.equal(Error("Error 2"))
+}
+
pub fn all_test() {
[Ok(1), Ok(2), Ok(3)]
|> result.all