F# – Converting to and from Units of Measure

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

I never fully recovered my workspace setup when I upgraded my laptop two years ago, and I still miss things today. If only I had known about Gitpod back then…

Learn more

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 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  3. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

Leave a Comment

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