diff --git a/docs/fsharp/language-reference/literals.md b/docs/fsharp/language-reference/literals.md index 8236b4543f4f8..2e51f05b2d618 100644 --- a/docs/fsharp/language-reference/literals.md +++ b/docs/fsharp/language-reference/literals.md @@ -48,7 +48,21 @@ let x = "a" + "b" // evaluated at run-time let y = "a" + "b" // evaluated at compile-time ``` -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 `[]` declaration, this code would fail to compile: +> [!NOTE] +> Functions cannot be used to compute `[]` values because literals must be determined at compile-time and cannot depend on runtime evaluation. + +### Why functions cannot compute literals + +The `[]` 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 `[]`. This restriction ensures that literals can be safely used in scenarios like pattern matching, attribute arguments, and interop with external functions. + +For instance, attempting to assign the result of a function to a literal will fail: + +```fsharp +[] +let yFunc() = "a" + "b" // error FS0267: this is not a valid constant expression +``` + +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 `[]` declaration, this code would fail to compile: ```fsharp [] @@ -77,6 +91,20 @@ let Literal2 = 1 ||| 64 let Literal3 = System.IO.FileAccess.Read ||| System.IO.FileAccess.Write ``` +### Example of concise pattern matching using Named literals + +Named literals can make pattern matching more concise by avoiding the need for `when` clauses or additional logic. For example: + +```fsharp +[] +let ErrorCode = 404 + +let handleResponse code = + match code with + | ErrorCode -> "Not Found" + | _ -> "Other Response" +``` + ## Remarks Named literals are useful for: