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

后端 未结 2 1534
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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-15 12:54

    You're right that removing unit information is a bad thing. You should create a few constants with appropriate units for conversion.

    let mPerKm = 1000.0
    let secondPerHour = 3600.0
    
    // val msToKmph : float -> float
    let msToKmph(speed : float) =
        speed / mPerKm * secondPerHour
    

    For km and m, a generic solution is to define a unit prefix k so it works for many UoMs which have kilo as a metric:

    [] type k
    
    let kilo = 1000.0<1/k>
    let secondPerHour = 3600.0
    
    // val msToKmph : float -> float
    let msToKmph(speed : float) =
        speed / kilo * secondPerHour
    

提交回复
热议问题