Concise pattern match on single case discriminated union in F#

雨燕双飞 提交于 2019-12-03 08:17:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!