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
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.
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.
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”.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With