I'm in the process of learning F# - and is currently looking into Units of Measure. I have a simple calculation returning meters per second, and I want to introduce a function converting it to kilometres per hour.
My code looks like this:
[<Measure>] type kg
[<Measure>] type s
[<Measure>] type m
[<Measure>] type km
[<Measure>] type h
let msToKmph(speed : float<m/s>) =
(float speed) * 3.6<km/h>
let gravityOnEarth = 9.81<m/s^2>
let heightOfJump = 3.5<m>
let speedOfImpact = sqrt (2.0 * gravityOnEarth * heightOfJump)
let speedOfImpactKmh = msToKmph(speedOfImpact)
This works - I get 8.28673639 m/s and 29.832251 km/h. What I am unsure of is if this is the best way to express the relationship between different units. Can this be done more elegantly?
For instance, the line doing (float speed) to remove the unit information from the speed parameter, to make the msToKmph return km/h. If I did not remove unit information before doing the calculation, the returned unit would be: km m/(h s)
First, your
msToKmph
is totally incorrect. Although it returns a correct return value, what it is actually doing, is it just drops the original<m/s>
value by converting to a plain, measurelessfloat
and then multiplies the measureless value to a3.6<km/h>
.To better express the relations between UoM's, consider this:
Note, all "magic numbers" are encapsulated within UoM converters, hence your formulas remain clean, e.g. they simply operate values and constants, but the UoM are calculated by the compiler.
Update: The philosophy of UoM conversion is that the conversion formulas should be something that has physical sense. The rule of thumb is whether your conversion value presents in reference books. In plain English,
3.6<km/h>
from above is useless, but1000.0<m/km>
just says, "there is 1000 m in 1 km", which makes sense.You can even improve
hrToSec
like this:This will make every value a well-known value found in reference books.
You're right that removing unit information is a bad thing. You should create a few constants with appropriate units for conversion.
For
km
andm
, a generic solution is to define a unit prefixk
so it works for many UoMs which have kilo as a metric: