@@ -326,33 +326,63 @@ pub fn to_string(bool: Bool) -> String {
326
326
327
327
/// Run a callback function if the given bool is `True`, otherwise return a
328
328
/// default value.
329
+ ///
330
+ /// With a `use` expression this function can simulate the early-return pattern
331
+ /// found in some other programming languages.
329
332
///
330
- /// This function is suitable for `use` expressions.
333
+ /// In a procedural language:
331
334
///
332
- /// ## Examples
335
+ /// ```js
336
+ /// if (predicate) return value;
337
+ /// // ...
338
+ /// ```
339
+ ///
340
+ /// In Gleam with a `use` expression:
333
341
///
334
342
/// ```gleam
335
- /// > let name = "Kamaka"
336
- /// > use <- guard(name != "", or: "Welcome!")
337
- /// > "Hello, " <> name
338
- /// "Hello, Kamaka"
343
+ /// use <- guard(when: predicate, return: value)
344
+ /// // ...
339
345
/// ```
340
346
///
347
+ /// Like everything in Gleam `use` is an expression, so it short circuits the
348
+ /// current block, not the entire function. As a result you can assign the value
349
+ /// to a variable:
350
+ ///
351
+ /// ```gleam
352
+ /// let x = {
353
+ /// use <- guard(when: predicate, return: value)
354
+ /// // ...
355
+ /// }
356
+ /// ```
357
+ ///
358
+ /// Note that unlike in procedural languages the `return` value is evaluated
359
+ /// even when the predicate is `False`, so it is advisable not to perform
360
+ /// expensive computation there.
361
+ ///
362
+ ///
363
+ /// ## Examples
364
+ ///
341
365
/// ```gleam
342
366
/// > let name = ""
343
- /// > use <- guard(name != "", or : "Welcome!")
367
+ /// > use <- guard(when: name == "", return : "Welcome!")
344
368
/// > "Hello, " <> name
345
369
/// "Welcome!"
346
370
/// ```
347
371
///
372
+ /// ```gleam
373
+ /// > let name = "Kamaka"
374
+ /// > use <- guard(when: name == "", return: "Welcome!")
375
+ /// > "Hello, " <> name
376
+ /// "Hello, Kamaka"
377
+ /// ```
348
378
///
349
379
pub fn guard (
350
- requirement : Bool ,
351
- or alternative : t,
352
- then consequence : fn ( ) -> t,
380
+ when requirement : Bool ,
381
+ return consequence : t,
382
+ otherwise alternative : fn ( ) -> t,
353
383
) -> t {
354
384
case requirement {
355
- True -> consequence ( )
356
- False -> alternative
385
+ True -> consequence
386
+ False -> alternative ( )
357
387
}
358
388
}
0 commit comments