f# - 是否可以对受歧视联合的基础形状进行模式匹配?

标签 f# functional-programming pattern-matching discriminated-union active-pattern

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/

相关文章:

variables - 定义和使用全局变量的最简单方法

Scala 表达式求值

python - 查找一定范围内有间隙的子列表

f# - 带有分号分隔符和预定义架构的 CsvProvider

.net - 在 F# 中显式实现接口(interface)

f# - F# 值名称中勾号(撇号)的用途?

functional-programming - Go 有标准的功能原语吗?

python - Python 中的函数式中缀实现

java - 如何使用正则表达式查找带有某些前缀的可选组

oop - Scala 的模式匹配是否违反了开放/封闭原则?