重用不同类型的度量单位

时间:2009-09-30 09:31:17

标签: f# units-of-measurement

Yesstill playing with units measure}

我刚开始第一次使用计量单位以外的其他东西。

开始复杂之后,我发现你可以在多个'类型'中重复使用度量单位。

[<Measure>] type mm

let a = 1<mm>
let b = 1.<mm>

现在我坐在这里想知道如何更新我现有的mm类型以反映这种可能性:

[<Measure>]
type mm =
    static member perMetre = 1000.0<mm/m>
    static member fromMetre (v:float<m>) = v * mm.perMetre
    static member toMetre (v:float<mm>) = v / mm.perMetre
    static member lift (v:float) = v * 1.0<mm>

问题:如何编写可以从mm转换为m(例如)的函数,该函数可以处理int<mm> -> int<m> AND {{1} }?

更新

感谢Kurt,这是新版本:

float<mm> -> float<m>

1 个答案:

答案 0 :(得分:2)

有时简单重载(如果你有参数):

[<Measure>]
type MM =
    static member perMetre = 1000.0<mm/m>
    static member fromMetre (v:float<m>) = v * MM.perMetre
    static member toMetre (v:float<mm>) = v / MM.perMetre
    [<OverloadIDAttribute("0")>]
    static member lift (v:float) = v * 1.0<mm>
    [<OverloadIDAttribute("1")>]
    static member lift (v:int) = v * 1<mm>