Pages

Thursday, September 22, 2011

Sample in detail - Use F# measure feature

In the sample package, I wrote a small sample to explore how to use measure unit in a bank system. Why I would like to present this sample? Because I want to show not only how to use measure unit on a single value but also how to use measure unit for a complex class. You can even treat this like a class template which takes measure unit as type.


[]type JPY
[]type CNY
type BankAccount<[]'u>() =
    let mutable balance : float<'u> = 0.0<_>
    member acct.HasLotsOfMoney = balance > (LanguagePrimitives.FloatWithMeasure 10000.0) //10000 units
    member acct.Deposit(amt) = balance <- balance + amt
    member acct.Withdraw(amt) = balance <- balance - amt

let MeasureSample5() =
    let a = BankAccount()
    a.Deposit(10.)

    let b = BankAccount()
    b.Deposit(10.)

    printfn "show how to deposit right currency to right account"

If you change the deposit incorrect currency into the account, you will get a compile time error. The tricky part is to use LanguagePrimitives.FloatWithMeasure in the sample. please make sure all constant in the type definition is always use  LanguagePrimitives.FloatWithMeasure.

No comments: