aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAhmad Sattar <thehabbos007@gmail.com>2020-06-18 19:04:03 +0200
committerLouis Pilfold <louis@lpil.uk>2020-06-18 21:55:52 +0100
commiteb0224d3f26c4fd90894bac5fb346c2aa3533efe (patch)
treeb254db7c49fe937f1c90f5169f263b7c72d5e2d7
parent7198eab42221bd99a0aa82795688aecc27533bc1 (diff)
downloadgleam_stdlib-eb0224d3f26c4fd90894bac5fb346c2aa3533efe.tar.gz
gleam_stdlib-eb0224d3f26c4fd90894bac5fb346c2aa3533efe.zip
Result or function
-rw-r--r--CHANGELOG.md1
-rw-r--r--src/gleam/result.gleam23
-rw-r--r--test/gleam/result_test.gleam18
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"))
+}