aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authortynanbe <contact@tynan.be>2023-11-14 12:54:11 -0600
committerLouis Pilfold <louis@lpil.uk>2023-11-18 10:33:46 +0000
commitb4c688a6b04aabae4ee5a64846cb223e7f8d4cc9 (patch)
treea637cac794bf75e46c17a4a22c069cb053b2c7b3 /src
parentd7db6233534f2cc7688f8c52081f5db4cf4da14a (diff)
downloadgleam_stdlib-b4c688a6b04aabae4ee5a64846cb223e7f8d4cc9.tar.gz
gleam_stdlib-b4c688a6b04aabae4ee5a64846cb223e7f8d4cc9.zip
Add bool.lazy_guard
Diffstat (limited to 'src')
-rw-r--r--src/gleam/bool.gleam40
1 files changed, 40 insertions, 0 deletions
diff --git a/src/gleam/bool.gleam b/src/gleam/bool.gleam
index 2cbe8a3..91bd6b7 100644
--- a/src/gleam/bool.gleam
+++ b/src/gleam/bool.gleam
@@ -386,3 +386,43 @@ pub fn guard(
False -> alternative()
}
}
+
+/// Runs a callback function if the given bool is `True`, otherwise runs an
+/// alternative callback function.
+///
+/// Useful when further computation should be delayed regardless of the given
+/// bool's value.
+///
+/// See [`guard`](#guard) for more info.
+///
+/// ## Examples
+///
+/// ```gleam
+/// > let name = "Kamaka"
+/// > let inquiry = fn() { "How may we address you?" }
+/// > use <- lazy_guard(when: name == "", return: inquiry)
+/// > "Hello, " <> name
+/// "Hello, Kamaka"
+/// ```
+///
+/// ```gleam
+/// > import gleam/int
+/// > let name = ""
+/// > let greeting = fn() { "Hello, " <> name }
+/// > use <- lazy_guard(when: name == "", otherwise: greeting)
+/// > let number = int.random(1, 99)
+/// > let name = "User " <> int.to_string(number)
+/// > "Welcome, " <> name
+/// "Welcome, User 54"
+/// ```
+///
+pub fn lazy_guard(
+ when requirement: Bool,
+ return consequence: fn() -> a,
+ otherwise alternative: fn() -> a,
+) -> a {
+ case requirement {
+ True -> consequence()
+ False -> alternative()
+ }
+}