F# 测量单位,铸造时不丢失测量类型
是否有保留单位的类型转换函数的内置版本,如果没有,我将如何制作它们?例如,使用这段代码,我如何将 intWithSecondsMeasure 转换为浮点数而不丢失度量或乘以 1.0
?
[<Measure>] type s
let intWithSecondsMeasure = 1<s>
let justAFloat = float intWithSecondsMeasure
Is there built in version of the type casting functions that preserves units and if not how would I make them? So for example with this code how would I cast intWithSecondsMeasure to a float without losing the measure or multiplying by 1.0<s>
?
[<Measure>] type s
let intWithSecondsMeasure = 1<s>
let justAFloat = float intWithSecondsMeasure
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
@kvb 提供的答案当然有效,但我不想使用
unbox
运算符进行此转换。有一种更好的内置方式,我认为应该将其编译为 NOP 到 IL(我没有检查过,但 unbox 可能最终会作为unbox
指令在 IL 中,因此添加了运行时类型检查)。在 F# 中进行单位转换的首选方法是
LanguagePrimitives.TypeWithMeasure
(The answer provided by @kvb certainly works, but I'd prefer not to use the
unbox
operator for this conversion. There's a better, built in way that I think should be compiled as a NOP to IL (I haven't checked but unbox is probably going to end up as aunbox
instruction in IL and thus adds a runtime type check).The preferred way to do unit conversions in F# is
LanguagePrimitives.TypeWithMeasure
(MSDN).我不认为有内置的方法可以做到这一点,但您可以轻松定义自己的保留单位转换函数:
I don't think that there's a built-in way to do it, but you can easily define your own unit-preserving conversion function:
我从 kvb 和 Johannes 的答案中编译了代码。
约翰内斯回答
kvb 答案并添加括号。
kvb 答案
I compiled the code from kvb and Johannes answers.
Johannes answer
kvb answer with parentheses added.
kvb answer
请参阅我对此问题的回答:
单位安全平方根
,它今天建议:
See my answer to this question:
Unit-safe square roots
which suggests this today: