Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise pattern match on single case discriminated union in F#

Say I have the following single case discriminated union:

type OrderId = OrderId of string 

At some point I need the actual string. The way I've found for extracting it is:

let id = match orderId with OrderId x -> x 

Is there a more concise way of doing this?

I understand that my use is a special case and the match makes sense in order to make sure you've covered the possibilities, just wondering if there's a way of doing something like:

let OrderId id = orderId 
like image 799
Geoff Avatar asked Sep 01 '12 23:09

Geoff


People also ask

When to use discriminated union?

Discriminated unions are useful for heterogeneous data; data that can have special cases, including valid and error cases; data that varies in type from one instance to another; and as an alternative for small object hierarchies. In addition, recursive discriminated unions are used to represent tree data structures.

What are discriminated union?

A discriminated union is a union data structure that holds various objects, with one of the objects identified directly by a discriminant. The discriminant is the first item to be serialized or deserialized. A discriminated union includes both a discriminant and a component.

What is pattern matching in F#?

Advertisements. Pattern matching allows you to “compare data with a logical structure or structures, decompose data into constituent parts, or extract information from data in various ways”.


2 Answers

You're almost there. Parentheses are required in order that the compiler interprets a let-bound as pattern matching:

let (OrderId id) = orderId 

If orderId is a parameter of a function, you can also use pattern matching directly there:

let extractId (OrderId id) = id 
like image 122
pad Avatar answered Oct 10 '22 20:10

pad


When you're using a discriminated union to hold a single value (which is a useful F# programming technique), then it might make sense to define it with a property for accessing the value:

type OrderId =    | OrderId of string    member x.Value = let (OrderId v) = x in v 

The implementation of Value is using the pattern matching using let as posted by pad. Now, if you have a value orderId of type OrderId, you can just write:

let id = orderId.Value 

However, the pattern matching using (OrderId id) is still quite useful, because property access will only work when the compiler already knows the type of orderId (so you would typically use pattern matching in function argument, but property access for other values).

like image 39
Tomas Petricek Avatar answered Oct 10 '22 20:10

Tomas Petricek