Question

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
Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top