Mar*_*tin 3 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 *)
Run Code Online (Sandbox Code Playgroud)
我可以插入什么代码来代替注释来创建该效果?
你可以做到
let highPrice =
let n = 200
match lowPrice with
| Dollar _ -> Dollar n
| Euro _ -> Euro n
Run Code Online (Sandbox Code Playgroud)
但计量单位可能更好.
编辑
或者,也许你想要
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)
Run Code Online (Sandbox Code Playgroud)