[英]Copying a union case but with a different value in F#
在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 *)
我可以插入什么代码来代替注释来创建该效果?
你可以做到
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)
我认为对于这类问题,使用测量单位更合适 - 比如
[<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
转换功能有点棘手,但它会做你想要的
您可以使用Reflection基于同一联合案例的现有值创建新的联合案例值。 为了实现这一点,只需添加实例成员Same
您的区分联合Same
,它首先从实例self
派生特定的联合案例,然后通过相同的联合案例构造一个新实例,但现在填充了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
你会得到highPrice : Currency = Euro 200
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.