Comparing F# discriminated union instances via pattern matching

痞子三分冷 提交于 2019-12-21 13:59:12

问题


Firstly, apologies for the poor title - I don't understand enough F# to describe the problem better.

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"

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.


回答1:


Does this work for you?

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" 


来源:https://stackoverflow.com/questions/12686911/comparing-f-discriminated-union-instances-via-pattern-matching

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