diff --git a/docs/fsharp/language-reference/lazy-expressions.md b/docs/fsharp/language-reference/lazy-expressions.md index dcf138aec4262..261d3877cd3cb 100644 --- a/docs/fsharp/language-reference/lazy-expressions.md +++ b/docs/fsharp/language-reference/lazy-expressions.md @@ -1,7 +1,7 @@ --- title: Lazy Expressions description: Learn how F# lazy expressions can improve the performance of your apps and libraries. -ms.date: 08/15/2020 +ms.date: 10/02/2025 --- # Lazy Expressions @@ -27,6 +27,21 @@ The following code illustrates the use of lazy expressions and the use of `Force Lazy evaluation, but not the `Lazy` type, is also used for sequences. For more information, see [Sequences](sequences.md). +## Formatting + +For multiline lazy expressions, place the opening parenthesis on the same line as the `lazy` keyword, with the expression body indented one level: + +```fsharp +let expensiveCalculation = + lazy ( + let step1 = performStep1() + let step2 = performStep2 step1 + step2 * 2 + ) +``` + +For more information on formatting lazy expressions, see the [F# formatting guide](../style-guide/formatting.md#formatting-lazy-expressions). + ## See also - [F# Language Reference](index.md) diff --git a/docs/fsharp/style-guide/formatting.md b/docs/fsharp/style-guide/formatting.md index fb7fc61872bd9..927ba4411270d 100644 --- a/docs/fsharp/style-guide/formatting.md +++ b/docs/fsharp/style-guide/formatting.md @@ -1,7 +1,7 @@ --- title: F# code formatting guidelines description: Learn guidelines for formatting F# code. -ms.date: 11/01/2023 +ms.date: 10/02/2025 --- # F# code formatting guidelines @@ -539,6 +539,41 @@ let useAddEntry () = bar () ``` +### Formatting lazy expressions + +When writing single-line lazy expressions, keep everything on one line: + +```fsharp +// ✔️ OK +let x = lazy (computeValue()) + +// ✔️ OK +let y = lazy (a + b) +``` + +For multiline lazy expressions, place the opening parenthesis on the same line as the `lazy` keyword, with the expression body indented one level and the closing parenthesis aligned with the opening: + +```fsharp +// ✔️ OK +let v = + lazy ( + // some code + let x = computeExpensiveValue() + let y = computeAnotherValue() + x + y + ) + +// ✔️ OK +let handler = + lazy ( + let connection = openConnection() + let data = fetchData connection + processData data + ) +``` + +This follows the same pattern as other function applications with multiline arguments. The opening parenthesis stays with `lazy`, and the expression is indented one level. + ### Formatting arithmetic and binary expressions Always use white space around binary arithmetic expressions: