开发者

Can I create own literal types on .NET (F#)

开发者 https://www.devze.com 2023-03-05 23:57 出处:网络
for example if I want literal type for Nullable(x) like 开发者_JS百科a let x = 6x // nullable literal type

for example if I want literal type for Nullable(x) like 开发者_JS百科a

let x = 6x // nullable literal type 

So is it real to make own literal types ?


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 through the following syntactic translation: xxxx<suffix>

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

For example, defining a module NumericLiteralZ as below permits the use of the literal form 32Z to generate a sequence of 32 'Z' characters. No literal syntax is available for numbers outside the range of 32-bit integers.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消