aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2023-01-21 13:28:32 +0000
committerLouis Pilfold <louis@lpil.uk>2023-02-26 18:51:30 +0000
commit68c3c2ec7fad21cf65f544fc0c4dc30519bd603c (patch)
tree51d1a562e1227b3e7a440d6551910b13e9f11b1f /src
parentfc751bf5e410e7f6c3ff781da38089f4fc9d8be9 (diff)
downloadgleam_stdlib-68c3c2ec7fad21cf65f544fc0c4dc30519bd603c.tar.gz
gleam_stdlib-68c3c2ec7fad21cf65f544fc0c4dc30519bd603c.zip
Rework bool.guard
Diffstat (limited to 'src')
-rw-r--r--src/gleam/bool.gleam54
1 files changed, 42 insertions, 12 deletions
diff --git a/src/gleam/bool.gleam b/src/gleam/bool.gleam
index 2d4b74d..5586153 100644
--- a/src/gleam/bool.gleam
+++ b/src/gleam/bool.gleam
@@ -326,33 +326,63 @@ pub fn to_string(bool: Bool) -> String {
/// Run a callback function if the given bool is `True`, otherwise return a
/// default value.
+///
+/// With a `use` expression this function can simulate the early-return pattern
+/// found in some other programming languages.
///
-/// This function is suitable for `use` expressions.
+/// In a procedural language:
///
-/// ## Examples
+/// ```js
+/// if (predicate) return value;
+/// // ...
+/// ```
+///
+/// In Gleam with a `use` expression:
///
/// ```gleam
-/// > let name = "Kamaka"
-/// > use <- guard(name != "", or: "Welcome!")
-/// > "Hello, " <> name
-/// "Hello, Kamaka"
+/// use <- guard(when: predicate, return: value)
+/// // ...
/// ```
///
+/// Like everything in Gleam `use` is an expression, so it short circuits the
+/// current block, not the entire function. As a result you can assign the value
+/// to a variable:
+///
+/// ```gleam
+/// let x = {
+/// use <- guard(when: predicate, return: value)
+/// // ...
+/// }
+/// ```
+///
+/// Note that unlike in procedural languages the `return` value is evaluated
+/// even when the predicate is `False`, so it is advisable not to perform
+/// expensive computation there.
+///
+///
+/// ## Examples
+///
/// ```gleam
/// > let name = ""
-/// > use <- guard(name != "", or: "Welcome!")
+/// > use <- guard(when: name == "", return: "Welcome!")
/// > "Hello, " <> name
/// "Welcome!"
/// ```
///
+/// ```gleam
+/// > let name = "Kamaka"
+/// > use <- guard(when: name == "", return: "Welcome!")
+/// > "Hello, " <> name
+/// "Hello, Kamaka"
+/// ```
///
pub fn guard(
- requirement: Bool,
- or alternative: t,
- then consequence: fn() -> t,
+ when requirement: Bool,
+ return consequence: t,
+ otherwise alternative: fn() -> t,
) -> t {
case requirement {
- True -> consequence()
- False -> alternative
+ True -> consequence
+ False -> alternative()
}
}