代码之家  ›  专栏  ›  技术社区  ›  Alex Gordon

如何将度量定义为其他度量的倍数

f#
  •  1
  • Alex Gordon  · 技术社区  · 6 年前

    我正试图定义 Isaron 成为 43.2 泰晤士报 Egg 但是我得到一个例外:

    [<Measure>] type Egg
    [<Measure>] type Isaron = (43.2)*(Egg)
    

    错误fs0618:类型中的文本无效

    如何正确定义此度量值?

    1 回复  |  直到 6 年前
        1
  •  4
  •   rmunn    6 年前

    您不在度量值类型中定义关系,而是在转换为类型或从类型转换为类型的函数中定义关系:

    [<Measure>] type Egg
    [<Measure>] type Isaron
    let toEgg (i : float<Isaron>) = i / 43.2<Isaron> * 1.0<Egg>
    let toIsaron (e : float<Egg>) = e / 1.0<Egg> * 43.2<Isaron>
    

    Scott Wlaschin's site 还有另一个例子,通过创建一个常量转换因子,以英尺和英寸为单位进行转换:

    [<Measure>] type Egg
    [<Measure>] type Isaron
    let isaronsPerEgg = 43.2<Isaron/Egg>
    let toEgg (i : float<Isaron>) = i / isaronsPerEgg
    let toIsaron (e : float<Egg>) = e * isaronsPerEgg