Is there a way to define a public literal (public const in C#) on a type? Apparently let bindings in types must be private and the Literal attribute can't be applied to members.
Use the [< Literal >] attribute. This does the magic you are looking for. In addition, putting the literal attribute on a value such as a string enables it to be used within pattern matching. For example:
// BAD - introduces new value named 'Name'
let Name = "Chris Smith"
match Console.ReadLine() with
| Name -> printfn "You entered my name! %s" Name
| _ -> printfn "You didn't enter my name"
// Good - uses the literal value, matches against the value Name
[<Literal>]
let NameLiteral = "Chris Smith"
match Console.ReadLine() with
| NameLiteral -> "You entered my name!"
| _ -> printfn "You didn't enter my name.
Edit: I see that the question is referring to how to put these within custom classes (and not modules). I do not know if you can expose a public const / public readonly field within F#, I'll look into it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With