If you’re read­ing this post, you prob­a­bly know about F#’s Units of Mea­sure already, it’s very use­ful when work­ing with real-world units and adds extra safety to code that needs to work with and con­vert from one unit to another.

Here’s a quick snip­pet that shows you how to define and use units-of-measure:

image

This code out­puts the fol­low­ing, note the units asso­ci­ated with the float values:

image

As you can see, units of mea­sure can also be com­pounded by mul­ti­pli­ca­tion or division!

If you have a func­tion that requires a int<m>, you won’t be able to call the func­tion with a nor­mal int, hence pro­vid­ing you with extra pro­tec­tion to ensure the cor­rect­ness of your appli­ca­tion because the unit of a numeric value is now a for­mal con­tract between a func­tion and its caller:

image

Hav­ing said that, there are cases where you want to be able to con­vert between an int and an int<m>. For instance, to pro­vide bet­ter inter­op­er­abil­ity with other .Net lan­guages, as units-of-measure only exists in F# there’s no way to cre­ate a numeric value with units-of-measure in C# (that I’m aware of anyway).

To con­vert from int<m> to int (or any other numeric type) is easy, just do a straight cast:

image

Going the other way is slightly more tricky, you can’t use int<m> to cast an int to an int<m>, but you can either mul­ti­ply the value with 1<m> or use the Int32WithMeasure method on the Lan­guagePrim­i­tives core module:

image

Share

Leave a Reply