gpt4 book ai didi

f# - 如何解构构造函数参数?

转载 作者:行者123 更新时间:2023-12-04 19:04:39 27 4
gpt4 key购买 nike

在 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

但我不知道如何做到这一点:
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.

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

最佳答案

不,language spec明确表示不:

primary-constr-args : attributesopt accessopt (simple-pat, ... , simplepat)
simple-pat :
| ident
| simple-pat : type

正如已经指出的,辅助构造函数是允许模式匹配的参数,但与主构造函数的区别在于主构造函数的每个参数都是函数参数和私有(private)字段声明。

如果 F# 允许在这里进行模式匹配,就会有一些模式会破坏这种单参数一字段的关系。
type DestructureInCtor(SingleCaseUnion _) = 
// doesn't declare a private field

或者:
type DestructureInCtor((a:int, b:int)) = 
// declares two private fields?

这不是不可想象的,但我猜测允许将模式匹配扩展到提供字段声明的复杂性超过了好处。

关于f# - 如何解构构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28171840/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com