How to model an entity with a currency?

136 Views Asked by At

I am trying to model a bond entity in F# using a unit of measure for the currency.

type Bond = {
     Isin: string
     Issuer: string
     Maturity: DateTime
     Price: float<???>
}

Let's assume that a static table with all the available/possible currencies is available.

type Currency = {
    Code : string
    Name : string
}

I can go for Price as float and PriceCurrency as string or even as a Currency type but I think that this is not ideal. Any ideas?

1

There are 1 best solutions below

5
Brian Berns On

I don't think F# units of measure are a good match for this use case, since the compiler isn't aware of the currency table. If you want to use units of measure anyway, each currency would have to be hard-coded into your source, like this:

open System

[<Measure>] type Dollar
[<Measure>] type Pound

type Bond =
    {
        Isin: string
        Issuer: string
        Maturity: DateTime
    }

type DollarBond =
    {
        Bond: Bond
        Price: float<Dollar>
    }

type PoundBond =
    {
        Bond: Bond
        Price: float<Pound>
    }

let poundsPerDollar = 0.73<Pound/Dollar>

let toPoundBond (dollarBond : DollarBond) =
    {
        Bond = dollarBond.Bond
        Price = dollarBond.Price * poundsPerDollar
    }

let dollarBond : DollarBond =
    {
        Bond = {
            Isin = "My isin"
            Issuer = "My issuer"
            Maturity = DateTime.Parse("1/1/2050")
        }
        Price = 1000.0<Dollar>
    }

printfn "%A" <| toPoundBond dollarBond

Related Questions in F#