5

まず、お粗末なタイトルについてお詫び申し上げます。私は、問題をより適切に説明するのに十分な F# を理解していません。

次の単純な 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"

お金をさまざまな通貨で表し、安全にお金 + お金を実行できるように (+) 演算子をオーバーロードしています。しかし、多くの通貨を持っている場合、match ステートメントを書くのは面倒になります。次のような表現方法はありますか。

match first, second with 
| _(x), _(y) -> _(x + y)

または、同じ結果を達成する別の方法はありますか? ここで説明されている制限のために、測定単位を考慮して破棄しました。

4

1 に答える 1

16

これはうまくいきますか?

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" 
于 2012-10-02T08:56:40.860 に答える