通过模式匹配比较F#区分的Union实例 [英] Comparing F# discriminated union instances via pattern matching
本文介绍了通过模式匹配比较F#区分的Union实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先,对标题不佳表示歉意-我对F#的理解不足,无法更好地描述问题.
Firstly, apologies for the poor title - I don't understand enough F# to describe the problem better.
考虑以下简单的DU:
Consider this simple DU:
type Money =
| USD of decimal
| GBP of decimal
| EUR of decimal
static member (+) (first: Money, second: Money) =
match first, second with
| USD(x), USD(y) -> USD(x + y)
| GBP(x), GBP(y) -> GBP(x + y)
| EUR(x), EUR(y) -> EUR(x + y)
| _ -> failwith "Different currencies"
我用不同的货币表示货币,并重载(+)运算符,以便我可以安全地进行Money + Money.但是,如果我有很多货币,那么match语句将变得很乏味.有什么表达方式:
I'm representing money in different currencies, and overloading the (+) operator so that I can safely do Money + Money. However, if I have many currencies then the match statement will become tedious to write. Is there any way of expressing something like:
match first, second with
| _(x), _(y) -> _(x + y)
Or is there a different way to achieve the same result? I've considered and discarded units of measure due to the limitations described here.
推荐答案
这对您有用吗?
type Kind = | USD | GBP | EUR
type Money =
| Money of Kind * decimal
static member (+) (first: Money, second: Money) =
match first, second with
| Money(k1,x), Money(k2,y) when k1=k2 -> Money(k1, x + y)
| _ -> failwith "Different currencies"
这篇关于通过模式匹配比较F#区分的Union实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文