Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Types, Records and Unions

Units of Measure and Type Abbreviations

Learn how F# catches unit mistakes at compile time with units of measure, when type abbreviations help, how enums differ from unions, and how to make small wrapper types that prevent bugs.

The best bugs to catch are the ones that never reach a test. A famous space probe was lost because one team computed in pound-force seconds and another in newton seconds. Both numbers were plain floats, so nothing complained. F# has a feature that makes this kind of mistake a compile error: units of measure. This lesson covers them, then three neighbours that help you name things well: type abbreviations, enums and small wrapper types.

Units of measure

Declare a unit with [<Measure>] and attach it to a number with angle brackets:

FSHARP
[<Measure>] type m      // metres
[<Measure>] type s      // seconds
[<Measure>] type kg

let distance = 100.0<m>
let time = 9.58<s>
let speed = distance / time      // float<m/s>

printfn "%.2f" (float speed)     // 10.44

The compiler tracks the unit through arithmetic: dividing metres by seconds gives float<m/s>. Adding two lengths is fine, but adding a length to a time is rejected:

FSHARP
let bad = distance + time        // error: units m and s do not match

Units exist only at compile time. At runtime a float<m> is an ordinary float, so there is no cost. Call float to strip the unit when you need the plain number, and multiply by 1.0<m> to add one.

Derived units and conversions

Units can be derived from others, and a conversion factor is an ordinary constant with a unit:

FSHARP
[<Measure>] type km
[<Measure>] type h

[<Measure>] type N = kg * m / s^2        // newton

let metresPerKm = 1000.0<m/km>
let toMetres (d: float<km>) = d * metresPerKm

let force = 2.0<kg> * 9.81<m/s^2>        // float<kg m/s^2>

Generic code can be unit-polymorphic with a measure type parameter:

FSHARP
let square (x: float<'u>) = x * x      // float<'u^2>

Units of measure work on float, float32, decimal and the integer types, but not on strings or custom types.

C# C# stand-in: unit mix-ups with a tiny wrapper type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Type abbreviations

A type abbreviation gives a long or unclear type another name:

FSHARP
type Name = string
type Scores = Map<string, int list>

let topScore (scores: Scores) name =
    scores |> Map.tryFind name |> Option.map List.max

An abbreviation is only an alias. Name and string are the same type, so you can pass a string wherever a Name is expected and the compiler will not stop you. That makes abbreviations good for readability and bad for safety. If you want safety, use a single-case union as shown in Discriminated Unions:

FSHARP
type Email = Email of string

Rule of thumb: abbreviate to shorten (Map<string, int list>), wrap to protect (Email).

Enums

An F# enum is a named set of integer constants, mainly for interop with .NET APIs and flags:

FSHARP
type Level =
    | Debug = 0
    | Info = 1
    | Error = 2

let l = Level.Info
printfn "%d" (int l)          // 1
printfn "%A" l                // Info

Differences from unions you should remember: an enum cases need explicit values, a match over one is not exhaustive (any int can be cast to Level, so you always need a wildcard), and cases carry no data. Mark an enum with [<Flags>] and give powers of two for combinable options:

FSHARP
[<System.Flags>]
type Access =
    | None = 0
    | Read = 1
    | Write = 2

let rw = Access.Read ||| Access.Write
printfn "%b" (rw.HasFlag Access.Write)   // true

For your own domain logic prefer a union; use an enum when a library demands one.

Choosing the right tool

flowchart LR
    A["Meaning of a number"] --> B["Units of measure<br/>(compile-time only)"]
    C["Long type name"] --> D["Type abbreviation<br/>(alias, no safety)"]
    E["Distinct id or text"] --> F["Single-case union<br/>(real new type)"]
    G["Library wants an int set"] --> H["Enum"]

Each tool solves a different problem, and the one that fits depends on whether you need safety, readability or interop.

C# C# stand-in: enum pitfalls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the compiler do with units of measure at runtime?

    Units are checked only at compile time and erased afterwards, so they cost nothing at runtime.
  2. 2. What is the type of 100.0<m> / 9.58<s>?

    The compiler divides the units along with the numbers.
  3. 3. Why is a type abbreviation like type Name = string weak protection?

    An abbreviation does not create a new type. Use a single-case union for a distinct type.
  4. 4. Why does a match over an enum usually need a wildcard case?

    Enums are open: values outside the named set are possible, so the compiler cannot prove completeness.

Summary

  • [<Measure>] types add compile-time units to numbers; the compiler multiplies and divides them for you and erases them at runtime.
  • Type abbreviations only rename types; single-case unions create a real new type.
  • Enums are integer constants for interop and flags; their matches are never exhaustive.
  • Pick the tool by need: safety, readability or interop.

Next: Classes, Interfaces and Object Expressions