Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# - public literal

Tags:

f#

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.

like image 636
Daniel Avatar asked Dec 02 '09 18:12

Daniel


1 Answers

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.

like image 144
Chris Smith Avatar answered Oct 22 '22 01:10

Chris Smith