Converting from m/s to km/h using F# Units of Measure

后端 未结 2 1530
Happy的楠姐
Happy的楠姐 2021-02-15 12:24

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

2条回答
  •  北海茫月
    2021-02-15 12:42

    First, your msToKmph is totally incorrect. Although it returns a correct return value, what it is actually doing, is it just drops the original value by converting to a plain, measureless float and then multiplies the measureless value to a 3.6.

    To better express the relations between UoM's, consider this:

    let kmToM = 1000.0  // relation between kilometers and meters
    let hrToSec = 3600.0 // relation between seconds and hours
    let msToKmph(speed : float) =
        speed / kmToM * hrToSec
    

    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 from above is useless, but 1000.0 just says, "there is 1000 m in 1 km", which makes sense.

    You can even improve hrToSec like this:

    let hrToSec2 = 60.0 * 60.0
    

    This will make every value a well-known value found in reference books.

提交回复
热议问题