@@ -326,33 +326,63 @@ pub fn to_string(bool: Bool) -> String {
326326
327327/// Run a callback function if the given bool is `True`, otherwise return a
328328/// default value.
329+ ///
330+ /// With a `use` expression this function can simulate the early-return pattern
331+ /// found in some other programming languages.
329332///
330- /// This function is suitable for `use` expressions.
333+ /// In a procedural language:
331334///
332- /// ## Examples
335+ /// ```js
336+ /// if (predicate) return value;
337+ /// // ...
338+ /// ```
339+ ///
340+ /// In Gleam with a `use` expression:
333341///
334342/// ```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+ /// // ...
339345/// ```
340346///
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+ ///
341365/// ```gleam
342366/// > let name = ""
343- /// > use <- guard(name != "", or : "Welcome!")
367+ /// > use <- guard(when: name == "", return : "Welcome!")
344368/// > "Hello, " <> name
345369/// "Welcome!"
346370/// ```
347371///
372+ /// ```gleam
373+ /// > let name = "Kamaka"
374+ /// > use <- guard(when: name == "", return: "Welcome!")
375+ /// > "Hello, " <> name
376+ /// "Hello, Kamaka"
377+ /// ```
348378///
349379pub 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,
353383) -> t {
354384 case requirement {
355- True -> consequence ( )
356- False -> alternative
385+ True -> consequence
386+ False -> alternative ( )
357387 }
358388}
0 commit comments