代码之家  ›  专栏  ›  技术社区  ›  Kevin Won

F#基于类型的度量单位转换

  •  2
  • Kevin Won  · 技术社区  · 16 年前

    我想用F#写一个“度量单位”转换器。

    我定义了两个度量单位, KWh 和 MWh 我正在尝试编写一个函数,在这两个函数之间进行转换,以匹配数值类型的模式。我可以有一个浮点,十进制,int的千瓦时转换成兆瓦时。

    [<Measure>]
    type KWh
    
    [<Measure>]
    type MWh
    
    // want to do this, but can't because x is not x:obj, 
    // its something like x:float<KWh>
    let toMWh x = 
        match x with
        | :? float<KWh>     -> x * (1.0<MWh>/1000.0<KWh>)
        | :? int<KWh>       -> // ...
    
    
    // above code not valid f#
    

    当我没有obj类型时,我不知道如何正确地在类型上分支。

    1 回复  |  直到 12 年前
        1
  •  3
  •   Brian    16 年前

    [<Measure>] 
    type KWh 
    
    [<Measure>] 
    type MWh 
    
    type Convert = 
        static member toMWh (x:float<KWh>) =  x * 1.0<MWh> / 1000.0<KWh>
        static member toMWh (x:int<KWh>) =  x * 1<MWh> / 1000<KWh>
    
    printfn "%d" (int(Convert.toMWh(5000<KWh>)))
    printfn "%f" (float(Convert.toMWh(5500.0<KWh>)))
    

    也就是说,有人可能会想出一个聪明的,类型安全的方法来处理它 inline