Units of Measure in F#
So, F# has units of measure built in. They’re pretty cool.
Essentially, you can declare units of measure, like this:
[<Measure>] type kg [<Measure>] type m [<Measure>] type s
Once you’ve done that, you can then associate these units of measure with numeric types.
let distance = 5.0<m> let time = 30<s> let weight = 50<kg>
You can combine measures, either with new values, or by multiplying or dividing already existing identifiers with units.
let speed = distance / (float time); let force = 5.0<kg m/s^2>
Finally, you can declare units of measure based on existing units of measure.
[<Measure>] type N = kg m/s^2 let forceNewton = 5.0<N> let equal = forceNewton = force
From that, we’ll get the output:
val equal : bool = true
If the numbers are different, the bool is false, and if the types are wrong, it fails with a type mismatch.
So, that’s a quick demonstration of Units of Measure in F#. They’re fantastic.
Leave A Comment