关于f#:重用不同类型的度量单位

Reusing units of measure across different types

(是的,仍在使用度量单位)

我第一次开始使用度量单位来表示浮点数以外的其他值。

在开始复杂化之后,我发现您可以跨多个"类型"重用度量单位。

1
2
3
4
[<Measure>] type mm

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

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

1
2
3
4
5
6
[<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 -> intfloat -> float

更新

感谢库尔特,这是新版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[<Measure>]
type mm =
    static member private perMetreFloat = 1000.0<mm/m>
    static member private perMetreInt = 1000<mm/m>
    [<OverloadIDAttribute("float")>]
    static member fromMetre (v:float<m>) = v * mm.perMetreFloat
    [<OverloadIDAttribute("float")>]
    static member toMetre (v:float<mm>) = v / mm.perMetreFloat
    [<OverloadIDAttribute("float")>]
    static member lift (v:float) = v * 1.0<mm>
    [<OverloadIDAttribute("int")>]
    static member fromMetre (v:int<m>) = v * mm.perMetreInt
    [<OverloadIDAttribute("int")>]
    static member toMetre (v:int<mm>) = v / mm.perMetreInt
    [<OverloadIDAttribute("int")>]
    static member lift (v:int) = v * 1<mm>


有时,简单的重载可以工作(如果您有一个参数):

1
2
3
4
5
6
7
8
9
[<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>