F# – Converting to and from Units of Measure

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 safe­ty to code that needs to work with and con­vert from one unit to anoth­er.

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

image

This code out­puts the fol­low­ing, note the units asso­ci­at­ed with the float val­ues:

image

As you can see, units of mea­sure can also be com­pound­ed by mul­ti­pli­ca­tion or divi­sion!

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 numer­ic val­ue is now a for­mal con­tract between a func­tion and its caller:

image

Hav­ing said that, there are cas­es 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­i­ty with oth­er .Net lan­guages, as units-of-mea­sure only exists in F# there’s no way to cre­ate a numer­ic val­ue with units-of-mea­sure in C# (that I’m aware of any­way).

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

image

Going the oth­er way is slight­ly more tricky, you can’t use int<m> to cast an int to an int<m>, but you can either mul­ti­ply the val­ue with 1<m> or use the Int32WithMeasure method on the Lan­guagePrim­i­tives core mod­ule:

image