F # Units of measurement metrics modeling metrics (micro, milli, nano)

According to this question: Fractional power of units of measure in F # for units of measure in F # is not supported fractional degree.

In my application, it’s useful to think about metric data sometime, for example. when working with seconds. Sometimes I need a result in milliseconds, sometimes in seconds.

The alternative I'm thinking about using right now is

[<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 enable calculations with two operations. Therefore 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 everything is beautiful and brilliant, but it is growing rapidly due to the fact that you want to support multiple units and multiple prefixes. Therefore, I think it would be necessary to bake this into a more general solution, but I don’t know where to start. I tried

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

but this will not work because f # complains and tells me that "Non-Zero constants cannot have common units" ...

Since I assume unit prefixes are a common problem, I think someone has solved this problem before. Is there a more idiomatic way to do unit prefixes in F #?

+7
source share
1 answer

You write a constant as 1000.0<(milli second)/second> representing 1000 milliseconds per second, but actually (you can do this as an algebraic simplification). milli simply means you need to multiply all units by 1000 to get a unit without milli.

So you can simplify the definition of milliPer (and milliSecondsPerSecond ) to just say:

 let milli = 1000.0<milli> 

Then it can be used with other types of measures:

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

I think that this should not lead to any complications anywhere in the code - this is an absolutely wonderful template when working with units (I saw people using the percent unit in the same way, but then the conversion is 0.01)

+7
source

All Articles