F#中单例区分工会的简明模式匹配 [英] Concise pattern match on single case discriminated union in F#

查看:79
本文介绍了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

是否有更简洁的方法?

我知道我的用法是一种特殊情况,为了确保您已经涵盖了所有可能性,这场比赛很有意义,只是想知道是否有一种方法可以做到:

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

推荐答案

您快到了.为了使编译器将let-bound解释为模式匹配,必须加括号:

You're almost there. Parentheses are required in order that the compiler interprets a let-bound as pattern matching:

let (OrderId id) = orderId

如果orderId是函数的参数,则也可以直接在其中使用模式匹配:

If orderId is a parameter of a function, you can also use pattern matching directly there:

let extractId (OrderId id) = id

这篇关于F#中单例区分工会的简明模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆