F# units of measure conversion based on type -
i'm trying write "unit of measure" converter in f#.
i have defined 2 units of measure, kwh , mwh , trying write function convert between 2 pattern match on numeric type.  have float, decimal, int of kwh convert mwh. 
[<measure>] type kwh  [<measure>] type mwh  // want this, can't because x not x:obj,  // x:float<kwh> let tomwh x =      match x     | :? float<kwh>     -> x * (1.0<mwh>/1000.0<kwh>)     | :? int<kwh>       -> // ...   // above code not valid f#   i'm not able figure out how correctly branch on type when don't have obj type.
honestly, i'd low-budget overloading solution:
[<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>)))   that said, may come clever, type-safe way inline (i'm not sure offhand if it's possible).  avoid run-time matching, since sacrifices static type-safety (which kinda point of units).  (also, impossible run-time matching of units anyway, since units erased during compilation.)
Comments
Post a Comment