在不同类型中重复使用计量单位
我刚刚开始使用除浮点以外的测量单位第一次。
在开始复杂之后,我发现您可以在多种“类型”中重复使用度量单位。
[<Measure>] type mm
let a = 1<mm>
let b = 1.<mm>
现在我坐在这里想知道如何更新我现有的 mm 类型以反映这种可能性:
[<Measure>]
type mm =
static member perMetre = 1000.0<mm/m>
static member fromMetre (v:float<m>) = v * mm.perMetre
static member toMetre (v:float<mm>) = v / mm.perMetre
static member lift (v:float) = v * 1.0<mm>
问题:如何编写一个可以从 mm
转换为 的函数>m
(比如说)可以处理 int
和 float
?
更新
感谢 Kurt,这是新版本:
[<Measure>]
type mm =
static member private perMetreFloat = 1000.0<mm/m>
static member private perMetreInt = 1000<mm/m>
[<OverloadIDAttribute("float")>]
static member fromMetre (v:float<m>) = v * mm.perMetreFloat
[<OverloadIDAttribute("float")>]
static member toMetre (v:float<mm>) = v / mm.perMetreFloat
[<OverloadIDAttribute("float")>]
static member lift (v:float) = v * 1.0<mm>
[<OverloadIDAttribute("int")>]
static member fromMetre (v:int<m>) = v * mm.perMetreInt
[<OverloadIDAttribute("int")>]
static member toMetre (v:int<mm>) = v / mm.perMetreInt
[<OverloadIDAttribute("int")>]
static member lift (v:int) = v * 1<mm>
(Yes, still playing with units of measure)
I've just started using units of measure for something other than float for the first time.
After starting off complicated, I discovered that you can re-use units of measure across multiple 'types'.
[<Measure>] type mm
let a = 1<mm>
let b = 1.<mm>
Now I'm sitting here wondering how to update my existing mm type to reflect this possibility:
[<Measure>]
type mm =
static member perMetre = 1000.0<mm/m>
static member fromMetre (v:float<m>) = v * mm.perMetre
static member toMetre (v:float<mm>) = v / mm.perMetre
static member lift (v:float) = v * 1.0<mm>
The question: How do I write a function that can convert from mm
to m
(say) that can handle int<mm> -> int<m>
AND float<mm> -> float<m>
?
UPDATE
Thanks to Kurt, here's the new version:
[<Measure>]
type mm =
static member private perMetreFloat = 1000.0<mm/m>
static member private perMetreInt = 1000<mm/m>
[<OverloadIDAttribute("float")>]
static member fromMetre (v:float<m>) = v * mm.perMetreFloat
[<OverloadIDAttribute("float")>]
static member toMetre (v:float<mm>) = v / mm.perMetreFloat
[<OverloadIDAttribute("float")>]
static member lift (v:float) = v * 1.0<mm>
[<OverloadIDAttribute("int")>]
static member fromMetre (v:int<m>) = v * mm.perMetreInt
[<OverloadIDAttribute("int")>]
static member toMetre (v:int<mm>) = v / mm.perMetreInt
[<OverloadIDAttribute("int")>]
static member lift (v:int) = v * 1<mm>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的重载有时会起作用(如果你有争论):
Simply overloading works sometimes (if you have an argument):