[英]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
You're almost there. 你快到了。 Parentheses are required in order that the compiler interprets a let-bound as pattern matching: 为了使编译器将let-bound解释为模式匹配,必须使用括号:
let (OrderId id) = orderId
If orderId
is a parameter of a function, you can also use pattern matching directly there: 如果orderId
是函数的参数,您还可以直接在那里使用模式匹配:
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: 当您使用区分联合来保存单个值(这是一种有用的F#编程技术)时,使用用于访问该值的属性来定义它可能是有意义的:
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. 的实现Value
是使用使用匹配模式let
张贴由垫。 Now, if you have a value orderId
of type OrderId
, you can just write: 现在,如果你有一个OrderId
类型的orderId
值,你可以写:
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). 但是,使用(OrderId id)
进行模式匹配仍然非常有用,因为只有当编译器已经知道orderId
的类型时,属性访问才会起作用(因此通常在函数参数中使用模式匹配,但对其他值使用属性访问)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.