diff options
author | tynanbe <contact@tynan.be> | 2023-11-14 12:54:11 -0600 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2023-11-18 10:33:46 +0000 |
commit | b4c688a6b04aabae4ee5a64846cb223e7f8d4cc9 (patch) | |
tree | a637cac794bf75e46c17a4a22c069cb053b2c7b3 | |
parent | d7db6233534f2cc7688f8c52081f5db4cf4da14a (diff) | |
download | gleam_stdlib-b4c688a6b04aabae4ee5a64846cb223e7f8d4cc9.tar.gz gleam_stdlib-b4c688a6b04aabae4ee5a64846cb223e7f8d4cc9.zip |
Add bool.lazy_guard
-rw-r--r-- | CHANGELOG.md | 4 | ||||
-rw-r--r-- | src/gleam/bool.gleam | 40 | ||||
-rw-r--r-- | test/gleam/bool_test.gleam | 12 |
3 files changed, 56 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d2149a..7a5b42a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased + +- The `bool` module gains the `lazy_guard` function. + ## v0.32.1 - 2023-11-11 - The printing of maps by `string.inspect` has been improved. 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() + } +} diff --git a/test/gleam/bool_test.gleam b/test/gleam/bool_test.gleam index 7e0cf05..964aab1 100644 --- a/test/gleam/bool_test.gleam +++ b/test/gleam/bool_test.gleam @@ -167,3 +167,15 @@ pub fn guard_test() { 1 } } + +pub fn lazy_guard_test() { + let assert 2 = { + use <- bool.lazy_guard(when: True, return: fn() { 2 }) + 1 + } + + let assert 1 = { + use <- bool.lazy_guard(when: False, return: fn() { 2 }) + 1 + } +} |