F# – Converting to and from Units of Measure

Yan Cui

I help clients go faster for less using serverless technologies.

If you’re reading this post, you probably know about F#’s Units of Measure already, it’s very useful when working with real-world units and adds extra safety to code that needs to work with and convert from one unit to another.

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

image

This code outputs the following, note the units associated with the float values:

image

As you can see, units of measure can also be compounded by multiplication or division!

If you have a function that requires a int<m>, you won’t be able to call the function with a normal int, hence providing you with extra protection to ensure the correctness of your application because the unit of a numeric value is now a formal contract between a function and its caller:

image

Having said that, there are cases where you want to be able to convert between an int and an int<m>. For instance, to provide better interoperability with other .Net languages, as units-of-measure only exists in F# there’s no way to create a numeric value with units-of-measure in C# (that I’m aware of anyway).

To convert 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 multiply the value with 1<m> or use the Int32WithMeasure method on the LanguagePrimitives core module:

image


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


Leave a Comment

Your email address will not be published. Required fields are marked *