Search code examples
f#functional-programmingdiscriminated-union

Copying a union case but with a different value in F#


In F#, I want to construct an instance (correct terminology?) of a discriminated union based on an existing instance. Example:

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 *)

What code could I insert in place of the comment to create that effect?


Solution

  • You could do

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

    but units of measure are probably better.

    EDIT

    Alternatively, maybe you want

    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)