aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorRobert Attard <robert.attard@mail.mcgill.ca>2022-01-09 13:17:37 -0500
committerGitHub <noreply@github.com>2022-01-09 18:17:37 +0000
commitc6f14db8fd21f66be20f3ef027df0d4dc5806bdb (patch)
treef702b447429da1acaa413a57a658ef983f644cbe /src
parent1d9085ea75c850ef270e1bec56c4d74721c6e9a0 (diff)
downloadgleam_stdlib-c6f14db8fd21f66be20f3ef027df0d4dc5806bdb.tar.gz
gleam_stdlib-c6f14db8fd21f66be20f3ef027df0d4dc5806bdb.zip
option.lazy_unwrap and option.lazy_or (#261)
Diffstat (limited to 'src')
-rw-r--r--src/gleam/option.gleam40
1 files changed, 40 insertions, 0 deletions
diff --git a/src/gleam/option.gleam b/src/gleam/option.gleam
index 20e85e9..4a097e8 100644
--- a/src/gleam/option.gleam
+++ b/src/gleam/option.gleam
@@ -115,6 +115,23 @@ pub fn unwrap(option: Option(a), or default: a) -> a {
}
}
+/// Extracts the value from an `Option`, evaluating the default function if the option is `None`.
+///
+/// ## Examples
+///
+/// > lazy_unwrap(Some(1), fn() { 0 })
+/// 1
+///
+/// > lazy_unwrap(None, fn() { 0 })
+/// 0
+///
+pub fn lazy_unwrap(option: Option(a), or default: fn() -> a) -> a {
+ case option {
+ Some(x) -> x
+ None -> default()
+ }
+}
+
/// Updates a value held within the `Some` of an `Option` by calling a given function
/// on it.
///
@@ -210,6 +227,29 @@ pub fn or(first: Option(a), second: Option(a)) -> Option(a) {
}
}
+/// Returns the first value if it is `Some`, otherwise evaluates the given function for a fallback value.
+///
+/// ## Examples
+///
+/// > lazy_or(Some(1), fn() { Some(2) })
+/// Some(1)
+///
+/// > lazy_or(Some(1), fn() { None })
+/// Some(1)
+///
+/// > lazy_or(None, fn() { Some(2) })
+/// Some(2)
+///
+/// > lazy_or(None, fn() { None })
+/// None
+///
+pub fn lazy_or(first: Option(a), second: fn() -> Option(a)) -> Option(a) {
+ case first {
+ Some(_) -> first
+ None -> second()
+ }
+}
+
/// Given a list of `Option`s,
/// returns only the values inside `Some`.
///