Skip to content

Commit 702157f

Browse files
authored
Add formatting guidance for multiline lazy expressions in F# (#48876)
1 parent d69c8ac commit 702157f

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

docs/fsharp/language-reference/lazy-expressions.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Lazy Expressions
33
description: Learn how F# lazy expressions can improve the performance of your apps and libraries.
4-
ms.date: 08/15/2020
4+
ms.date: 10/02/2025
55
---
66
# Lazy Expressions
77

@@ -27,6 +27,21 @@ The following code illustrates the use of lazy expressions and the use of `Force
2727

2828
Lazy evaluation, but not the `Lazy` type, is also used for sequences. For more information, see [Sequences](sequences.md).
2929

30+
## Formatting
31+
32+
For multiline lazy expressions, place the opening parenthesis on the same line as the `lazy` keyword, with the expression body indented one level:
33+
34+
```fsharp
35+
let expensiveCalculation =
36+
lazy (
37+
let step1 = performStep1()
38+
let step2 = performStep2 step1
39+
step2 * 2
40+
)
41+
```
42+
43+
For more information on formatting lazy expressions, see the [F# formatting guide](../style-guide/formatting.md#formatting-lazy-expressions).
44+
3045
## See also
3146

3247
- [F# Language Reference](index.md)

docs/fsharp/style-guide/formatting.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: F# code formatting guidelines
33
description: Learn guidelines for formatting F# code.
4-
ms.date: 11/01/2023
4+
ms.date: 10/02/2025
55
---
66
# F# code formatting guidelines
77

@@ -539,6 +539,41 @@ let useAddEntry () =
539539
bar ()
540540
```
541541

542+
### Formatting lazy expressions
543+
544+
When writing single-line lazy expressions, keep everything on one line:
545+
546+
```fsharp
547+
// ✔️ OK
548+
let x = lazy (computeValue())
549+
550+
// ✔️ OK
551+
let y = lazy (a + b)
552+
```
553+
554+
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:
555+
556+
```fsharp
557+
// ✔️ OK
558+
let v =
559+
lazy (
560+
// some code
561+
let x = computeExpensiveValue()
562+
let y = computeAnotherValue()
563+
x + y
564+
)
565+
566+
// ✔️ OK
567+
let handler =
568+
lazy (
569+
let connection = openConnection()
570+
let data = fetchData connection
571+
processData data
572+
)
573+
```
574+
575+
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.
576+
542577
### Formatting arithmetic and binary expressions
543578

544579
Always use white space around binary arithmetic expressions:

0 commit comments

Comments
 (0)