Unit of measures in F# bring the ability to add type information to basic numeric types. This leads to more safety against unit mismatch, such as using seconds where milliseconds were expected. While it is possible to deal with unit of measures using classes, having the feature built into the language leads to more concise code.
Unit of measures in F# can be used to add type safety to any value which type is related to others. The following shows the computation of values of different types:
[<Measure>] type dollar
[<Measure>] type pound
[<Measure>] type hour
[<Measure>] type week
[<Measure>] type year
let hoursBilledPerWeek = 32.0<hour/week>
let weeksWorkedPerYear = 47.0<week/year>
let dollarsPerHour = 100.0<dollar/hour>
let exchangeRate = 1.45<dollar/pound>
let poundsPerYear = dollarsPerHour * hoursBilledPerWeek * weeksWorkedPerYear / exchangeRate
// the value and type of poundsPerYear is: float<pound/year> = 103724.1379
Some APIs could also benefit from units of measure. This makes some types of bugs obsolete, such as passing the wrong measure as a parameter. One common example is Thread.Sleep(10)
, where the function accept an int and the unit is defined in the documentation. Using unit of measures the method can be wrapped to provide a stricter API:
let sleep (time : int<ms>) = Thread.Sleep(time / 1<ms>)
sleep 10<ms>
Calling sleep with 10 seconds results in a compilation error:
Error Type mismatch. Expecting a
int<ms>
but given a
int<s>
Measures such as time often need to be converted. Conversion is done using multiplication or division, as they would be done in a formula. Using static members, a conversion can be done like this:
[<Measure>] type ft
[<Measure>] type inch = static member perFoot = 12.0<inch/ft>
let inches = 1.0<ft> * inch.perFoot;
Applications dealing with physics may need to represent complex units such as a newton. Using compound unit of measure, combinations of simpler units are done like the following example:
let distance = 1.0<m>
let time = 2.0<sec>
let speed = 2.0<m/sec>
let acceleration = 2.0<m/sec^2>
let force = 5.0<kg m/sec^2>
One caveat to mention is that F# unit of measures cannot be exposed as part of a public API to other .NET languages like C#. This is because unit of measures are not inside the CLR, they are a language construct stored in assembly metadata.