是否有可能对歧视联盟的底层形状进行模式匹配? [英] Is is possible to pattern match on the underlying shape of a discriminated union?

查看:165
本文介绍了是否有可能对歧视联盟的底层形状进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

F#是否支持使用标准以外的标准对区分联合成员实例进行模式匹配标识符模式

例如,假设我想匹配数据的基础形状,并且想要考虑任何与<$ c $无论DU如何对值进行分类,都可以使用c> int * int 形状。

For example, imagine that I want to match on the underlying shape of the data and I want to consider anything with an int * int shape, regardless of how the DU classifies the value. Is

下面是我现在要做的:

Here's how I'd do it now:

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"

我希望更接近以下内容:

I'd like something closer to the following:

let shapeName = 
  match asCase1 with
  | (x,y) -> "pair" 
  | _ -> "atom"

是否有一些目前在F#中支持的类似表达式语法,或者我坚持明确地指定所有情况?

Is there some similarly expressive syntax that is currently supported in F# or am I stuck with explicitly specifying all cases?

注意:我知道我可以找出如何使用反射来查找我想要的信息,但是我对此没有兴趣一个解决方案。

推荐答案

以下是活动模式答案

Here is the active pattern answer

let (|Pair|_|) input = 
    match input with
    |BinaryCase1(a,b)
    |BinaryCase2(a,b) -> Some(a,b)
    | _ -> None

及用法

and the usage

match asCase1 with |Pair(a,b) -> printfn "matched" | _ -> ();;

这篇关于是否有可能对歧视联盟的底层形状进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆