问题
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
回答1:
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
回答2:
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).
来源:https://stackoverflow.com/questions/12232187/concise-pattern-match-on-single-case-discriminated-union-in-f