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.
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