F# 是否支持按 Identifier pattern 以外的标准对有区别的联合成员实例进行模式匹配?
例如,假设我想要匹配数据的基础形状,并且想要考虑具有 int * int
形状的任何内容,无论 DU 如何对值进行分类。是
这是我现在要做的:
type ExampleDU =
| BinaryCase1 of x:int * y:int
| BinaryCase2 of x:int * y:int
| UnaryCase1 of x:int
let underlyingValue = (1,2)
let asCase1 = BinaryCase1 underlyingValue
let asCase2 = BinaryCase2 underlyingValue
let shapeName =
match asCase1 with
| BinaryCase1 (x,y) | BinaryCase2 (x,y) -> "pair" // is this possible without explicitly writing the name for each part?
| _ -> "atom"
我想要更接近以下内容的内容:
let shapeName =
match asCase1 with
| (x,y) -> "pair"
| _ -> "atom"
F# 目前是否支持一些类似的表达语法,或者我是否坚持显式指定所有情况?
注意:我知道我可以弄清楚如何通过反射找到我想要的信息,但我对这样的解决方案不感兴趣。
最佳答案
这是事件模式答案
let (|Pair|_|) input =
match input with
|BinaryCase1(a,b)
|BinaryCase2(a,b) -> Some(a,b)
| _ -> None
以及用法
match asCase1 with |Pair(a,b) -> printfn "matched" | _ -> ();;
关于f# - 是否可以对受歧视联合的基础形状进行模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34352698/