如何构造构造函数参数?

Tim*_*son 5 f# pattern-matching

在F#中,我可以在语法中的各个位置使用模式匹配.

例如:

// Given this type...
type SingleCaseUnion = | SingleCaseUnion of int

/// ...I can do this:
let destructureInFunc (SingleCaseUnion n) =
    printfn "%d" n

// ...and this:
type DestructureInMethod() =
    member t.M(SingleCaseUnion n) =
        printfn "%d" n
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何做到这一点:

type DestructureInCtor(SingleCaseUnion n) =
    do printfn "%d" n

//  type DestructureInCtor(SingleCaseUnion n) =
//  ---------------------------------------^
//
// stdin(3,40): error FS0010: Unexpected identifier in type definition. Expected ')' or other token.
Run Code Online (Sandbox Code Playgroud)

我是否有错误的语法,或者F#不支持构造函数参数中的模式匹配?

Tim*_*ers 5

不,语言规范明确说不:

primary-constr-args : attributesopt accessopt (simple-pat, ... , simplepat)
simple-pat :
 | ident
 | simple-pat : type
Run Code Online (Sandbox Code Playgroud)

正如已经指出的那样,辅助构造函数是允许模式匹配的参数,但与主构造函数的不同之处在于每个主要参数都是函数参数私有字段声明.

如果F#允许模式匹配,那么会有一些模式会破坏这种单参数一字段关系.

type DestructureInCtor(SingleCaseUnion _) = 
    // doesn't declare a private field
Run Code Online (Sandbox Code Playgroud)

要么:

type DestructureInCtor((a:int, b:int)) = 
    // declares two private fields? 
Run Code Online (Sandbox Code Playgroud)

这可能有用,但我猜测允许将模式匹配扩展到提供字段声明的复杂性超过了它的好处,这并不是不可思议的.