Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In F# is it possible to create a pattern that will match multiple cases of a discriminate union?

Lets say I have a discriminated union like this:

type Example = 
   |Foo of string
   |Bar of int
   |Baz of int
   |Qux of int
   |NoValue

Is there any concise way to complete the following function without specifying all the remaining cases

let doIt (ex:Example) = 
    match ex with
    | Foo(_) -> 0
    | NoValue -> -1

Such that the pattern will generically handle the remaining similarly structured union cases the same way. In the example code, it would mean a single case statement for Bar,Baz, and Qux that would behave like the following.

    | Bar(i) -> i

I didn't see anything in the language reference that would allow this type of matching but I'm curious if it's possible.

like image 706
Andrew M Avatar asked Jun 30 '13 18:06

Andrew M


People also ask

What is force (F)?

Force is represented by the symbol F. The original form of Newton's second law states that the net force acting upon an object is equal to the rate at which its momentum changes with time.

What is Fahrenheit (°F)?

Definition: The Fahrenheit (symbol: °F) is a unit of temperature that was widely used prior to metrication.

What are words that end in F?

11-letter words that end in f. bulletproof. tamperproof. neckerchief. bullmastiff. mantelshelf. leatherleaf.


1 Answers

Not quite as concise as you want, but you can do something like this using the OR pattern:

let doIt (ex:Example) =
    match ex with
    | Foo(_) -> 0
    | NoValue -> -1
    | Bar(i) | Baz(i) | Qux(i) -> i;;

It does, however, eliminate the duplication of all of the (possibly) complex portion of that case.

For the sake of further illustration, you can also do this even if your cases don't match exactly like so:

type Example =
  | Foo of string
  | Bar of int * int
  | Baz of int
  | Qux of int
  | NoValue

let doIt (ex:Example) =
    match ex with
    | Foo _ -> 0
    | NoValue -> -1
    | Bar(i,_) | Baz i | Qux i -> i
like image 55
N_A Avatar answered Nov 15 '22 10:11

N_A