How do you print the resulting units using units of measure in F#?

懵懂的女人 提交于 2019-12-10 16:19:59

问题


I am beginning to learn how to use units of measure in F# but I haven't found the answer to this simple question yet. How do you print the resultant units after a calculation. I know that FSI prints them so they should be available somehow.

For example:

[<Measure>] type m;;

[<Measure>] type s;;

let d = 10<m>;;
val d : int<m> = 10

let t = 2<s>;;
val t : int<s> = 2

I want to do something like this:

printfn "Results: %A %A" (d / t) (UOM (d / t));;
"Results: 5 m/s"

Thanks in advance


回答1:


Unfortunately, this is not possible.

Units of measure exist only at compile time. When you compile the program, they will be ereased (because .NET doesn't have any way of representing units for types). This means that at the runtime, the result of your calculation will be just float. I don't think there is any way other than just writing units as string in your code...

There was a related question some time ago. It has some more details and also explains why you cannot get information about units using reflection.

  • Why can not use reflection in f#


来源:https://stackoverflow.com/questions/4359767/how-do-you-print-the-resulting-units-using-units-of-measure-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!