复制工会案例但在F#中使用不同的值

时间:2012-03-14 02:02:31

标签: f# functional-programming discriminated-union

在F#中,我想基于现有实例构造一个有区别的联合的实例(正确的术语?)。例如:

type union Currency =
    | Dollar of int
    | Euro of int

let lowPrice = Dollar 100 (* or, it could be *) let lowPrice = Euro 100
let highPrice = (* of the same union case as lowPrice but with value 200 *)

我可以使用哪些代码代替注释来创建该效果?

3 个答案:

答案 0 :(得分:5)

你可以做到

let highPrice =
    let n = 200
    match lowPrice with
    | Dollar _ -> Dollar n
    | Euro _ -> Euro n

但计量单位可能更好。

修改

或者,也许你想要

type MoneyType = Dollar | Euro
type Currency = Currency of MoneyType * int
let lowPrice = Currency(Dollar, 100)
let highPrice = 
    match lowPrice with
    | Currency(kind, _) -> Currency(kind, 200)

答案 1 :(得分:2)

我认为对于这类问题,使用度量单位更合适 - 比如

[<Measure>] type Dollar
[<Measure>] type Euro

let lowprice = 100<Dollar>
let inline _highprice (newv:int) (oldv:int<'t>) : int<'t> = 
    LanguagePrimitives.Int32WithMeasure newv
let highprice = _highprice 200 lowprice

转换功能有点棘手,但它会做你想做的事情

答案 2 :(得分:0)

您可以使用Reflection基于同一联合案例的现有值创建新的联合案例值。为了实现这一点,只需将实例成员Same添加到您的区分联合,它首先从实例self派生特定的联合案例,然后通过相同的联合案例构造一个新实例,但现在填充{ {1}}:

newVal

现在将其应用于open Microsoft.FSharp.Reflection type Currency = | Dollar of int | Euro of int member self.Same newVal : Currency = FSharpValue.MakeUnion(fst (FSharpValue.GetUnionFields(self, typeof<Currency>)), [|newVal|]) |> unbox 以下的值

lowPrice

你会得到let lowPrice = Euro(100) let highPrice = lowPrice.Same 200