Should I enforce a type with F# units of measure? [Style vs generality]

Viewed 69

This question relates to F# units of measure.

Should I enforce a type for a unit I am using.

For example should I enforce that seconds are always a float?

let asSeconds time = float(time)*1.0<second>

This seems a tad bit restrictive, since NASA may want to use decimal. On the other hand I don't know how to convert a generic a' into a unit a'<seconds>. The issue I am facing is that some application level functions do NOT use units, but some library stuff DO use units.

P.S. This is lightly related to my previous question

1 Answers

should I enforce that seconds are always a float?

I don't think you could really enforce this, since units of measure are not inherently tied to a specific numeric type. For example, both of the following would be legal:

let a = 1<second>     // a : int<second>
let b = 1.0<second>   // b : float<second>

I don't know how to convert a generic 'a into a unit 'a<seconds>.

This is an interesting question, but I don't think it's possible to write a generic version of asSeconds, because units of measure can only be applied to literals, and literals are never generic in F#. So you can't write time<second> or time * GenericOne<second>.

Bottom line, when converting from a dimensionless value to a dimensioned value you have to pick a specific numeric type, like float. But this doesn't mean that you can force all values of that UOM to have that numeric type.

Related