简体   繁体   English

F#测量单位建模度量标准前缀(微,毫,纳米)

[英]F# Units of Measurement modeling metric prefix (micro, milli, nano)

As per this question: Fractional power of units of measures in F# there are no fractional powers supported for units of measure in F#. 根据这个问题: F#中度量单位的分数幂没有F#中的度量单位支持的分数幂。

In my application, it is beneficial to think of data with a metric prefix sometime, eg when dealing with seconds. 在我的应用程序中,有时候使用度量前缀来考虑数据是有益的,例如在处理秒时。 Sometimes I need a result in milli-seconds, sometimes in seconds. 有时我需要一毫秒的结果,有时甚至几秒钟。

The alternative I'm currently thinking about using is this 我正在考虑使用的另一种选择是这个

[<Measure>] type milli
[<Measure>] type second

let a = 10.0<second>;
let b = 10.0<milli*second>

which gives me: 这给了我:

val a : float<second> = 10.0
val b : float<milli second> = 10.0

Now I want to allow calculations with the two operations. 现在我想允许使用这两个操作进行计算。 So I could do 所以我能做到

let milliSecondsPerSecond = 1000.0<(milli*second)/second>

let a = 10.0<second>;
let b = 10.0<milli*second>

(a*milliSecondsPerSecond) + b

which gives me exactly what I wanted 这给了我我想要的东西

val it : float<milli second> = 10010.0

Now, this is all nice and shiny but grows out of hand quickly when you want to support multiple units and multiple prefixes. 现在,当你想要支持多个单元和多个前缀时,这一切都很好而且有光泽但很快就会失控。 So I think it would be either necessary to bake this into a more generic solution, but don't know where to start. 所以我认为有必要将其烘焙成更通用的解决方案,但不知道从哪里开始。 I tried 我试过了

let milliPer<'a> = 1000.0<(milli * 'a) / 'a>

but that won't work because f# complains and tells me "Non-Zero constants cannot have generic units"... 但这不起作用,因为f#抱怨并告诉我“非零常数不能有通用单位”......

Since I imagine that unit prefixes are a common problem, I imagine someone has solved this problem before. 由于我认为单位前缀是一个常见问题,我想有人之前已经解决了这个问题。 Is there a more idiomatic way to do unit prefixes in F#? 在F#中是否有更惯用的方法来做单位前缀?

You write the constant as 1000.0<(milli second)/second> representing 1000 milliseconds per second, but actually (you can do this as an algebraic simplification) "milli" just means that you need to multiply whatever unit by 1000 to get the unit without the "milli" prefix. 您将常量写为1000.0<(milli second)/second>表示每秒1000毫秒,但实际上(您可以将此作为代数简化)“milli”只表示您需要将任何单位乘以1000以获得单位没有“milli”前缀。

So, you can simplify your definition of milliPer (and milliSecondsPerSecond ) to just say: 因此,您可以简化milliPer (和milliSecondsPerSecond )的定义,只需说:

let milli = 1000.0<milli>

Then it is possible to use it with other kinds of measures: 然后可以将其与其他措施一起使用:

(10.0<second> * milli) + 10.0<milli second>   
(10.0<meter> * milli) + 10.0<milli meter>

I think this should not lead to any complications anywhere in the code - it is a perfectly fine pattern when working with units (I've seen people using a unit of percent similarly, but then the conversion is 0.01) 我认为这不会导致代码中任何地方出现任何复杂问题 - 使用单位时这是一个非常精细的模式(我看到人们使用percent单位,但转换为0.01)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM