Is is possible to pattern match on the underlying shape of a discriminated union?

末鹿安然 提交于 2019-12-06 11:17:13

问题


Does F# support pattern matching of a discriminated union member instance by criteria other than the Identifier pattern?

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"

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

Note: I know that I could figure out how to find the information that I want with reflection, but I'm not interested in such a solution.


回答1:


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" | _ -> ();;


来源:https://stackoverflow.com/questions/34352698/is-is-possible-to-pattern-match-on-the-underlying-shape-of-a-discriminated-union

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!