Establish Units of Measure Relationships With a Quantity of Another Unit

后端 未结 1 1729
慢半拍i
慢半拍i 2021-01-20 15:31

I realize that you can express relationships with dimensions of units, like

[] type cc = cm^3
         


        
1条回答
  •  清酒与你
    2021-01-20 16:32

    In short: no.

    Units of measure are annotations on primitives. Period. As you probably know, they will be deleted during compilation.

    So here's their fundamental limitation: you cannot attach any kind of functionality to them, because they will all turn into plain old floats.

    The compiler will check that your expressions are dimensionally valid, but (for now) it does not automatically generate or insert any sort of 'default' type-conversion functions.

    You must write and use those functions yourself, and the best you can do is to make them as straightforward as possible.

    Here's how I'd organise your example:

    [] type mm    
    [] type mt
    
    // first, I like to define basic functions to quickly annotate dimensionless values
    let mm = (*) 1.0
    let mt = (*) 1.0
    
    // we define a constant conversion
    let MmPerMt = 1000.0
    
    // (though nothing forbids us from defining any conversion we want, and the compiler cannot privilege one over another)
    let INeverPaidAttentionInGradeSchool = 12345
    
    // for ease of use, we bake the conversion constant into functions
    let MtToMm = (*) MmPerMt
    
    // usage
    let someUserInputInMeters = "12414.23"
    
    let desiredValueInMillimeters = someUserInputInMeters
                                    |> float
                                    |> mt
                                    |> MtToMm
    

    0 讨论(0)
提交回复
热议问题