问题
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