Can I create my own literals in .NET (F #)

for example if I need a literal type for Nullable (x) like

let x = 6x // nullable literal type 

Is it really possible to create your own literals?

+3
source share
1 answer

Yes, you can

F # spec:

Integer literals with the suffixes Q, R, Z, I, N, G are used for user-defined and library-defined types using the following syntax translation: xxxxx <suffix>

  • For xxxx = 0 - NumericLiteral.FromZero ()
  • For xxxx = 1 - NumericLiteral.FromOne ()
  • For xxxx in the Int32 range - NumericLiteral.FromInt32 (xxxx)
  • For xxxx in Int64 range - NumericLiteral.FromInt64 (xxxx)
  • For other numbers, NumericLiteral.FromString ("xxxx")

, NumericLiteralZ, , 32Z 32 "Z". , 32- , .

module NumericLiteralZ =
    let FromZero() = ""
    let FromOne() = "Z"
    let FromInt32 n = String.replicate n "Z"

// nullables
open System
module NumericLiteralN = 
    let FromZero()          = Nullable(0)
    let FromOne()           = Nullable(1)
    let FromInt32(i : int)  = Nullable(i)

printfn "%A" 0N
printfn "%A" 1N
printfn "%A" 100N.HasValue
+11

All Articles