Skip to content
LumenaryAcademy
Practice 60 min

Type inference, generics and units of measure

How F# works out your types, when to help it, generic and inline code, units the compiler checks, and F#'s object-oriented side.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Strong types, few annotations

So far you have written very few types, yet every program was statically typed. That is F#'s type inference at work, and it is one of the reasons F# code is so compact. This lesson looks under the bonnet: how inference works, when it needs a hint, and how to write generic code deliberately rather than by accident.

Then come two features that show what a strong type system can do beyond catching typos. Units of measure let the compiler check that you never add metres to seconds or euros to shillings, at no run-time cost. And F#'s object-oriented features (classes, interfaces, object expressions) let you meet .NET libraries on their own terms and structure the parts of a program where objects are the right tool.

IntuitionH

How inference works

F# uses a version of the Hindley–Milner type inference algorithm, developed for ML in the 1970s. In outline, the compiler gives every unknown a type variable, collects equations from how values are used (x + 1 says x has the same type as 1; passing w to String.length says w is a string), and solves them. Whatever is left unconstrained becomes generic.

F# adds one important practical rule: inference flows from left to right and from top to bottom. When the compiler meets w.Length, it must already know the type of w, because .Length could belong to a string, an array, a list or a hundred other .NET types. That is why the order of a pipeline matters, and why some programs need an annotation.

fsharp
// Inference flows from left to right, top to bottom.
let lengths (words: string list) = words |> List.map (fun w -> w.Length)   // annotation needed for .Length
let lengths2 words = words |> List.map (fun (w: string) -> w.Length)      // or here
let lengths3 (words: string list) = words |> List.map String.length         // or use a function with a known type
printfn "%A %A %A" (lengths [ "sol" ]) (lengths2 [ "luna" ]) (lengths3 [ "terra" ])

// Automatic generalisation: nothing forces a type, so these are generic.
let firstAndLast xs = (List.head xs, List.last xs)
printfn "%A %A" (firstAndLast [ 1; 2; 3 ]) (firstAndLast [ "a"; "b" ])

// Explicit generic parameters and constraints.
let largest<'T when 'T: comparison> (items: 'T list) = List.max items
printfn "%d %s" (largest [ 3; 9; 4 ]) (largest [ "pear"; "apple"; "quince" ])

let countDistinct (items: 'T list) = items |> List.distinct |> List.length   // needs 'T: equality, inferred
printfn "%d" (countDistinct [ 'a'; 'b'; 'a'; 'c' ])

// inline functions resolve operators at each call site, so this works for every numeric type.
let inline sumOfSquares xs = xs |> List.sumBy (fun x -> x * x)
printfn "%d %.2f %M" (sumOfSquares [ 1; 2; 3 ]) (sumOfSquares [ 0.5; 1.5 ]) (sumOfSquares [ 0.1m; 0.2m ])

// Type abbreviations name a type without creating a new one.
type Coordinates = float * float
let distance ((x1, y1): Coordinates) ((x2, y2): Coordinates) = sqrt ((x2 - x1) ** 2.0 + (y2 - y1) ** 2.0)
printfn "%.1f" (distance (0.0, 0.0) (3.0, 4.0))

It prints:

text
[3] [4] [5]
(1, 3) ("a", "b")
9 quince
3
14 2.50 0.05
5.0
  • Where annotations are needed. In lengths, the parameter annotation tells the compiler what w is before it sees w.Length. lengths2 annotates the lambda instead, and lengths3 avoids the member access altogether by using String.length, a function whose type is already known. Pipelines help inference: in words |> List.map (fun w -> ...), the type of words is known before the lambda is checked.
  • Automatic generalisation. firstAndLast works on lists of anything, because nothing in it constrains the element type.
  • Explicit generics. largest<'T when 'T: comparison> names its type parameter and states a constraint: List.max needs elements that can be compared. Common constraints are comparison, equality, struct, not struct, null and interface constraints such as 'T :> IDisposable. Often, as in countDistinct, you can write 'T and let F# infer the constraint.
  • inline for numeric code. An ordinary function using * is fixed to one numeric type. Marking it inline makes the compiler insert its body at each call site and resolve * there, so sumOfSquares works for int, float and decimal alike. Under the hood this uses statically resolved type parameters. Use inline for small numeric helpers; it is not a general performance switch.
  • Type abbreviations such as type Coordinates = float * float give a name to an existing type. They do not create a new type: any float * float is accepted. For a genuinely distinct type, use a single-case union or a record.

Professional F# code annotates public functions (in libraries and module signatures), which documents the API and stabilises it, and leaves local values and lambdas to inference. When a type error is confusing, adding annotations step by step is the standard way to locate it.

Worked examplesH

Units of measure

In 1999, NASA lost the Mars Climate Orbiter because ground software produced thruster data in English (imperial) units while the navigation software expected metric units, and nothing converted between them. Every number was correct; their units were not. F#'s units of measure make that kind of mistake a compile-time error.

Definition— Unit of measure

A type-level annotation on a numeric value, declared as a type marked with the Measure attribute, as in the program below. Numbers carry units (5.0<m>), arithmetic combines them (metres divided by seconds gives m/s), and adding or comparing values with different units is a type error. Units are checked by the compiler and erased at run time: a float<m> is an ordinary float in the compiled program.

fsharp
// Units of measure: the compiler checks dimensions, and they cost nothing at run time.
[<Measure>] type m
[<Measure>] type s
[<Measure>] type km
[<Measure>] type h
[<Measure>] type kg

let metresPerKm = 1000.0<m/km>
let secondsPerHour = 3600.0<s/h>

let distance = 42.195<km>
let time = 2.0<h> + 50.0<h> / 60.0
let speed = distance / time                       // inferred: float<km/h>
let speedMs = speed * metresPerKm / secondsPerHour // float<m/s>

printfn "Marathon in 2h50: %.2f km/h = %.2f m/s" (float speed) (float speedMs)

// Kinetic energy: kg m^2 / s^2. Define the derived unit as an abbreviation.
[<Measure>] type J = kg m^2 / s^2
let kineticEnergy (mass: float<kg>) (v: float<m/s>) : float<J> = 0.5 * mass * v * v
printfn "A 70 kg runner at that speed: %.0f J" (float (kineticEnergy 70.0<kg> speedMs))

// Units work on decimals too: a classic use is keeping currencies apart.
[<Measure>] type EUR
[<Measure>] type KES

let eurToKes = 140.0m<KES/EUR>   // an illustrative fixed rate
let hotel = 85.0m<EUR>
let taxi = 1500.0m<KES>
let totalKes = hotel * eurToKes + taxi
printfn "Trip total: %M KES" (decimal totalKes)
// let wrong = hotel + taxi   // does not compile: the units EUR and KES do not match

It prints:

text
Marathon in 2h50: 14.89 km/h = 4.14 m/s
A 70 kg runner at that speed: 599 J
Trip total: 13400.00 KES

The compiler inferred that speed is in km/h and speedMs in m/s, simply by following the arithmetic. Conversion factors are themselves values with units (1000.0<m/km>), so a conversion multiplies the units correctly too. Derived units, such as the joule, are declared as abbreviations (kg m^2 / s^2), and kineticEnergy declares that it returns joules: if the formula were wrong, say mass * v without the second v, it would not compile.

The same mechanism keeps currencies apart, a favourite use in financial F# code: euros and Kenyan shillings cannot be added without an exchange rate whose units say KES/EUR. (The rate in the program is a made-up round number, not a real one.) Uncomment the last line and the program no longer compiles; the compiler reports error FS0001: The unit of measure 'KES' does not match the unit of measure 'EUR'.

To leave the world of units (to print, or to call a .NET method), convert with float or decimal, which strips the unit. To enter it, multiply a plain number by 1.0<m>, or use LanguagePrimitives.FloatWithMeasure. Because units are erased, they cost nothing at run time and are invisible to C# callers, who see plain double and decimal values.

Worked examplesH

Modules and smart constructors

Types become an abstraction tool when you can control how values are created. F# code is organised in modules (named groups of types, functions and values; List and Option are modules) and namespaces, and module members can be private or internal. Combining a module with a union whose case is private gives the standard F# idiom for validated types, often called a smart constructor:

fsharp
// A module groups related types and functions. A private case hides the constructor,
// so the only way to get an EmailAddress is through create, which validates.
module EmailAddress =
    type T = private EmailAddress of string

    let create (text: string) =
        let trimmed = text.Trim()
        if trimmed.Length > 3 && trimmed.Contains '@' && not (trimmed.EndsWith '@') then
            Ok(EmailAddress(trimmed.ToLowerInvariant()))
        else
            Error $"'{text}' is not a valid email address"

    let value (EmailAddress text) = text

module Percentage =
    type T = private Percentage of float

    let create value =
        if value >= 0.0 && value <= 100.0 then Some(Percentage value) else None

    let value (Percentage p) = p
    let applyTo amount (Percentage p) = amount * p / 100.0

for raw in [ "  Amara@Example.ORG "; "not-an-email"; "x@" ] do
    match EmailAddress.create raw with
    | Ok email -> printfn "valid: %s" (EmailAddress.value email)
    | Error message -> printfn "%s" message

match Percentage.create 15.0 with
| Some tip -> printfn "15%% tip on 80.00 is %.2f" (Percentage.applyTo 80.0 tip)
| None -> printfn "invalid percentage"

printfn "150%% is valid? %b" (Percentage.create 150.0 |> Option.isSome)
// EmailAddress.EmailAddress "bad"   // does not compile outside the module: the case is private

It prints:

text
valid: amara@example.org
'not-an-email' is not a valid email address
'x@' is not a valid email address
15% tip on 80.00 is 12.00
150% is valid? false

Outside the EmailAddress module, nobody can write EmailAddress "bad": trying it fails with error FS1093: The union cases or fields of the type 'T' are not accessible from this code location. The only way to obtain an EmailAddress.T is EmailAddress.create, which validates and normalises. So any function that takes an EmailAddress.T can trust it completely, without checking again. The naming convention, a module containing a type T with create and value functions, is common in F# codebases; others name the type after the module and put both side by side.

Notice how this combines the lessons so far: a single-case union for a distinct type, Result and option for creation that can fail, and a module to control access. In a compiled project you would often go one step further and write a signature file (.fsi), which lists exactly what a module exposes, the F# equivalent of a header or an interface for the whole module.

Worked examplesH

Classes, interfaces and object expressions

F# is a full .NET language, so it can define classes and interfaces that C# code can use, and implement interfaces that .NET libraries require. Idiomatic F# uses these features where they fit: for objects that encapsulate changing state or resources, for implementing framework interfaces, and at the boundary with C#.

fsharp
// F# is functional-first, but it has full support for .NET classes and interfaces.
type INotifier =
    abstract Send: recipient: string * message: string -> unit

type Account(owner: string, notifier: INotifier) =
    let mutable balance = 0m                     // private state

    member _.Owner = owner
    member _.Balance = balance

    member this.Deposit(amount: decimal) =
        if amount <= 0m then invalidArg (nameof amount) "must be positive"
        balance <- balance + amount
        notifier.Send(owner, $"Deposited {amount}; balance {this.Balance}")

    override _.ToString() = $"{owner}: {balance}"

// A real implementation...
type ConsoleNotifier() =
    interface INotifier with
        member _.Send(recipient, message) = printfn "[to %s] %s" recipient message

// ...and an object expression: an implementation made on the spot, ideal for tests.
let sent = ResizeArray<string>()
let recorder =
    { new INotifier with
        member _.Send(_, message) = sent.Add message }

let live = Account("Leilani", ConsoleNotifier())
live.Deposit 120m

let tested = Account("Tariq", recorder)
tested.Deposit 50m
tested.Deposit 25m
printfn "%O; recorded %d messages, last: %s" tested sent.Count sent[sent.Count - 1]

try
    tested.Deposit -5m
with :? System.ArgumentException as ex ->
    printfn "refused: %s" ex.Message

It prints:

text
[to Leilani] Deposited 120; balance 120
Tariq: 75; recorded 2 messages, last: Deposited 25; balance 75
refused: must be positive (Parameter 'amount')
  • Interfaces are declared with abstract members. INotifier.Send takes a tuple, the .NET method style.
  • Classes have a primary constructor in their header: type Account(owner: string, notifier: INotifier). let bindings inside are private fields; let mutable balance is private mutable state. member defines public properties and methods; _ or this names the instance. override replaces an inherited method such as ToString.
  • Implementing an interface uses interface ... with. Interface members in F# are explicit: to call Send on a ConsoleNotifier, you must view it as an INotifier. That rarely matters, because code usually depends on the interface anyway.
  • Object expressions, { new INotifier with ... }, create an object implementing an interface without declaring a class. They are perfect for test doubles, as recorder shows: it captures messages in a list instead of sending them. They can capture local values, which makes them a lightweight alternative to small classes.
  • invalidArg raises an ArgumentException naming the parameter, and nameof gets the name from the code, so it stays correct when the parameter is renamed. %O formats a value with its ToString.

When should you write a class in F#? When you need encapsulated mutable state (a cache, a connection, a simulation object), when a .NET framework requires one (ASP.NET Core controllers, Entity Framework entities, UI view models), or when you publish an API for C# developers. For plain data, records and unions remain better; for behaviour, functions in modules. Many F# programs contain no classes at all, and many contain a few at their edges.

ExplanationH

Type design in practice

A few habits from teams that use F# in production:

  • Be concrete first. It is tempting to make everything generic because inference makes it free. Generic code is harder to read and to explain in error messages. Write the concrete version; generalise when a second use appears.
  • Wrap primitives that matter. Identifiers, money, email addresses, percentages: wrapping them in single-case unions or units costs a line and prevents whole families of mix-ups. Leave throwaway strings and counters alone.
  • Validate once, at the edge. Parse raw input into validated types (with smart constructors) as soon as it enters the program, and let the rest of the code accept only the validated types. Bugs cannot then hide in "this should have been checked earlier".
  • Annotate and document the surface. Public functions get type annotations and /// documentation comments; libraries often add signature files. Internal code stays lean.
  • Keep object-oriented code at the edges. Classes that wrap a framework, a connection or a cache sit at the boundary of the program; the domain logic in the middle is records, unions and functions.
History & global context

Where these ideas come from

The inference algorithm F# uses was discovered twice: by the logician J. Roger Hindley in 1969, for combinatory logic, and independently by Robin Milner in 1978, for ML; Luis Damas and Milner later proved its key properties, which is why it is also called Damas–Milner inference. Its great strength is that it always finds the most general type for an expression, which is where F#'s automatic generalisation comes from. F# extends it to cope with .NET's overloading and subtyping, which is the reason for the left-to-right rule.

Units of measure came from the PhD research of Andrew Kennedy at Cambridge in the 1990s, on checking physical dimensions with types. Kennedy later joined Microsoft Research in Cambridge, where he built the feature into F#; it arrived in 2008, and F# remains one of very few mainstream languages with dimension checking built into its type system. Libraries in other languages offer similar checks, usually at some cost in complexity or speed.

Common misconceptionsH

Common misconceptions

Misconception

"If inference can work out every type, annotations are bad style." Annotations on public functions are documentation that the compiler checks, and they stop a change inside a function from silently changing its signature for every caller. Leave local code unannotated; annotate the surface.

Misconception

"Units of measure slow numeric code down." Units are erased during compilation; a float<m/s> is a plain float at run time, with no wrapper and no check.

Misconception

"Using classes in F# is un-idiomatic." Using classes for everything is un-idiomatic. Using one where you need encapsulated state, a framework type or a C#-friendly API is exactly what the language provides them for.

Exercises

Exercises

1. Type inference, generics and units of measure

Warm-upComputational

What does this script print?

let inline sumOfSquares xs = xs |> List.sumBy (fun x -> x * x)
printfn "%d" (sumOfSquares [ 2; 3; 4 ])

2. Type inference, generics and units of measure

CoreComputational

What does this script print?

[<Measure>] type m
let d = 5.0<m>
printfn "%s %.1f" (d.GetType().Name) (float d)

3. Type inference, generics and units of measure

CoreHuman

With [<Measure>] type m and [<Measure>] type s declared, which expression fails to compile?

Choose one

4. Type inference, generics and units of measure

CoreComputational

What does this script print?

type ICounter =
    abstract Next: unit -> int

let makeCounter start =
    let mutable n = start
    { new ICounter with
        member _.Next() =
            n <- n + 1
            n }

let c = makeCounter 10
let d = makeCounter 100
printfn "%d %d %d" (c.Next()) (c.Next()) (d.Next())

5. Type inference, generics and units of measure

CoreHuman

In the lesson's EmailAddress module the union case is private. What does that guarantee?

Choose one

6. Type inference, generics and units of measure

StretchHuman

Why does let lengths words = words |> List.map (fun w -> w.Length) need a type annotation somewhere, while let lengths3 words = words |> List.map String.length does not?

Choose one

Further reading and resources

  • Type inference · MicrosoftHow the compiler infers types, and how annotations interact with it.
  • Units of measure · MicrosoftDefining units, derived units, conversions and generic units.
  • Object expressions · MicrosoftImplementing interfaces on the fly.
  • Mars Climate Orbiter · NASAThe mission lost in 1999 because two software systems used different units.