Skip to content

Commit 3fdb4bb

Browse files
shethaaditAdit ShethBillWagner
authored
Enhanced F# Literals Documentation with Comprehensive Examples and Advanced Use Cases (#44527)
* Fixed bug 36921. * Resolved comments. * Update docs/fsharp/language-reference/literals.md --------- Co-authored-by: Adit Sheth <[email protected]> Co-authored-by: Bill Wagner <[email protected]>
1 parent 00ec590 commit 3fdb4bb

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

docs/fsharp/language-reference/literals.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,21 @@ let x = "a" + "b" // evaluated at run-time
4848
let y = "a" + "b" // evaluated at compile-time
4949
```
5050

51-
For example, this distinction matters when calling an [external function](functions/external-functions.md), because `DllImport` is an attribute that needs to know the value of `myDLL` during compilation. Without the `[<Literal>]` declaration, this code would fail to compile:
51+
> [!NOTE]
52+
> Functions cannot be used to compute `[<Literal>]` values because literals must be determined at compile-time and cannot depend on runtime evaluation.
53+
54+
### Why functions cannot compute literals
55+
56+
The `[<Literal>]` attribute requires values to be known at compile-time. Functions, even if they seem to produce constant outputs, are evaluated at runtime, making them unsuitable for `[<Literal>]`. This restriction ensures that literals can be safely used in scenarios like pattern matching, attribute arguments, and interop with external functions.
57+
58+
For instance, attempting to assign the result of a function to a literal will fail:
59+
60+
```fsharp
61+
[<Literal>]
62+
let yFunc() = "a" + "b" // error FS0267: this is not a valid constant expression
63+
```
64+
65+
This distinction also matters when calling an [external function](functions/external-functions.md). For example, `DllImport` is an attribute that needs to know the value of `myDLL` during compilation. Without the `[<Literal>]` declaration, this code would fail to compile:
5266

5367
```fsharp
5468
[<Literal>]
@@ -77,6 +91,20 @@ let Literal2 = 1 ||| 64
7791
let Literal3 = System.IO.FileAccess.Read ||| System.IO.FileAccess.Write
7892
```
7993

94+
### Example of concise pattern matching using Named literals
95+
96+
Named literals can make pattern matching more concise by avoiding the need for `when` clauses or additional logic. For example:
97+
98+
```fsharp
99+
[<Literal>]
100+
let ErrorCode = 404
101+
102+
let handleResponse code =
103+
match code with
104+
| ErrorCode -> "Not Found"
105+
| _ -> "Other Response"
106+
```
107+
80108
## Remarks
81109

82110
Named literals are useful for:

0 commit comments

Comments
 (0)