是否有保留单位的类型转换函数的内置版本,如果没有,我将如何制作它们?因此,例如使用此代码,我如何将 intWithSecondsMeasure 转换为浮点数而不丢失度量值或乘以1.0<s>
?
[<Measure>] type s
let intWithSecondsMeasure = 1<s>
let justAFloat = float intWithSecondsMeasure
是否有保留单位的类型转换函数的内置版本,如果没有,我将如何制作它们?因此,例如使用此代码,我如何将 intWithSecondsMeasure 转换为浮点数而不丢失度量值或乘以1.0<s>
?
[<Measure>] type s
let intWithSecondsMeasure = 1<s>
let justAFloat = float intWithSecondsMeasure
@kvb 提供的答案当然有效,但我不希望使用unbox
运算符进行此转换。有一种更好的内置方式,我认为应该将其编译为 IL 的 NOP(我尚未检查,但 unbox 可能最终会作为unbox
IL 中的指令,因此添加了运行时类型检查)。
在 F# 中进行单位转换的首选方法是LanguagePrimitives.TypeWithMeasure
( MSDN )。
let inline float32toFloat (x:float32<'u>) : float<'u> =
x |> float |> LanguagePrimitives.FloatWithMeasure
我认为没有内置的方法可以做到这一点,但您可以轻松定义自己的单位保留转换函数:
let float_unit (x:int<'u>) : float<'u> = unbox float x
let floatWithSecondsMeasure = float_unit intWithSecondsMeasure
我从 kvb 和 Johannes 的答案中编译了代码。
约翰内斯回答
let float32toFloat (x:int<'u>) : float<'u> =
x |> float |> LanguagePrimitives.FloatWithMeasure
.method public static float64 float32toFloat(int32 x) cil managed
{
// Code size 3 (0x3)
.maxstack 8
IL_0000: ldarg.0
IL_0001: conv.r8
IL_0002: ret
} // end of method Program::float32toFloat
添加括号的 kvb 答案。
let float_unit (x:int<'u>) : float<'u> = unbox (float x)
.method public static float64 float_unit(int32 x) cil managed
{
// Code size 13 (0xd)
.maxstack 8
IL_0000: ldarg.0
IL_0001: conv.r8
IL_0002: box [mscorlib]System.Double
IL_0007: unbox.any [mscorlib]System.Double
IL_000c: ret
} // end of method Program::float_unit
kvb回答
let float_unit (x:int<'u>) : float<'u> = unbox float x
.method public static float64 float_unit(int32 x) cil managed
{
// Code size 19 (0x13)
.maxstack 8
IL_0000: newobj instance void Program/float_unit@4::.ctor()
IL_0005: call !!0 [FSharp.Core]Microsoft.FSharp.Core.LanguagePrimitives/IntrinsicFunctions::UnboxGeneric<class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2<int32,float64>>(object)
IL_000a: ldarg.0
IL_000b: tail.
IL_000d: callvirt instance !1 class [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2<int32,float64>::Invoke(!0)
IL_0012: ret
} // end of method Program::float_unit
看我对这个问题的回答:
这表明今天:
[<Measure>]
type s
let intWithSecondsMeasure = 1<s>
let intUtoFloatU< [<Measure>] 'u>( x : int<'u> ) : float<'u> = //'
let i = int x // drop the units
let f = float i // cast
box f :?> float<'u> //' restore the units
let floatWithS = intUtoFloatU intWithSecondsMeasure