F# · Lesson 4

Records & Tuples

Tuples and destructuring, records, copy-and-update, structural equality, record patterns, anonymous records and members.

7 min read

In short

  • Tuples group a few values: (3, 4) has type int * int
  • Records: : in the type, = in values, all fields required
  • { r with Field = x } copies; nothing is mutated
  • Records, tuples and lists compare by value
  • Patterns take records apart in match, let and parameters

Records and tuples are how F# groups data. Records are what you'd use a TypeScript type/interface plus object literals for. They come with immutability, value equality and copying built in.

Tuples

A tuple is an ad-hoc group of values, written with commas:

▶ Try
let point = (3, 4)                    // int * int
let product = ("Widget", 9.99, true)  // string * float * bool
let pair = 1, "one"                   // parentheses are optional
▶ Try
const point: [number, number] = [3, 4];

The type int * int reads "an int and an int". Take tuples apart by destructuring:

▶ Try
let (x, y) = point
let name, price, _ = product          // _ ignores a value
let first = fst pair                  // fst / snd: pairs only

Tuples are perfect for returning several values from a function and for short-lived pairs inside a pipeline:

▶ Try
let minMax (xs: int list) : int * int = (List.min xs, List.max xs)
let lowest, highest = minMax [ 4; 1; 9 ]

[ ("apples", 3); ("pears", 5) ] |> List.map (fun (fruit, count) -> $"{count} {fruit}")

.NET methods with out parameters return tuples in F#: System.Int32.TryParse "42" is (true, 42).

Use tuples for 2–3 values with obvious meaning. Once you're asking "what was the third element again?", it's time for a record.

Records

▶ Try
type Customer =
    { Id: int
      Name: string
      Email: string
      IsVip: bool }
▶ Try
type Customer = { id: number; name: string; email: string; isVip: boolean };
  • type Customer = declares a new type. Field names are PascalCase by convention.
  • In the type definition, fields use Name: type. On one line, separate them with ;.
  • All fields are required and immutable (unless you mark one mutable). There are no optional ? fields; a field that might be missing is typed string option.

Create a record by listing its fields. F# finds the type from the field names, with no new and no type name needed:

▶ Try
let ada = { Id = 1; Name = "Ada"; Email = "ada@example.com"; IsVip = false }
let name = ada.Name

Note the switch: : in type definitions, = in values.

Copy-and-update

You never modify a record. You make a new one with some fields changed:

▶ Try
let vipAda = { ada with IsVip = true; Email = "ada@vip.example.com" }
▶ Try
const vipAda = { ...ada, isVip: true, email: "ada@vip.example.com" };

Unlike a TS spread, you can't add fields that don't exist or change a field's type. Nested records are updated by nesting the expression: { order with Customer = { order.Customer with Name = "Bob" } }.

Structural equality

Records, tuples, lists and unions compare by value, automatically:

▶ Try
let a = { Id = 1; Name = "Ada"; Email = "ada@example.com"; IsVip = false }
let b = { Id = 1; Name = "Ada"; Email = "ada@example.com"; IsVip = false }
a = b                      // true!
(1, "x") = (1, "x")        // true

In TypeScript a === b would be false (two different objects), and you'd reach for a deep-equal library. In F#, equality "just works", which is why tests can write expectEqual expectedRecord actual. Records and tuples also get comparison (field by field, in declaration order), so you can sort them or use them as Map keys and in List.distinct/groupBy.

Pattern matching on records

match compares a value against patterns, top to bottom, and runs the first one that fits:

▶ Try
let describe (customer: Customer) : string =
    match customer with
    | { IsVip = true; Name = name } -> $"VIP {name}"
    | { Email = email } when email.EndsWith("@ourcompany.com") -> "staff"
    | _ -> "regular customer"
  • match value with starts it; each line | pattern -> result is an arm. All arms return the same type.
  • { IsVip = true; Name = name } matches records whose IsVip is true, and binds Name to a new variable name. Fields you don't mention are ignored.
  • when adds a guard: an extra boolean condition.
  • _ matches anything (the default: of a switch).

You can destructure records directly in let and in parameters, too:

▶ Try
let { Name = customerName } = ada
let greet { Name = name } = $"Hello, {name}"

The next topic goes much deeper into match.

Anonymous records

Need a one-off shape without declaring a type? Use {| ... |}:

▶ Try
let summary = {| Total = 42.5m; Count = 3 |}
summary.Total                                   // 42.5M
let bigger = {| summary with Count = 4 |}       // copy-and-update works too

These are the closest thing to TS object literals with inferred types. They're handy for query results, intermediate pipeline steps, and JSON. They have structural equality but can't be used in record patterns, and they're not great as public API types (no name to refer to).

Members on records

Records can have properties and methods, for convenient dot-access:

▶ Try
type LineItem =
    { Product: string
      Quantity: int
      UnitPrice: decimal }

    member this.Total = decimal this.Quantity * this.UnitPrice
    member this.WithQuantity(quantity: int) = { this with Quantity = quantity }
    static member Create(product: string, price: decimal) =
        { Product = product; Quantity = 1; UnitPrice = price }

let item = LineItem.Create("Pen", 1.50m)
item.Total                          // 1.50M
item.WithQuantity(3).Total          // 4.50M
  • member this.Total = ... is a property: no parentheses, recomputed on every access. this is the name you choose for the current instance (any name works; this, x and _ are common).
  • member this.WithQuantity(quantity: int) is a method. Methods take tuple-style arguments, like .NET.
  • static member belongs to the type itself, like a TS static method.
  • override this.ToString() = ... customises how it prints.

Idiomatic F# often keeps behaviour in plain functions (in a module next to the type), and uses members for small, obvious things like computed properties and operators.

Money: use decimal

0.1 + 0.2 = 0.30000000000000004 with float. decimal literals end in m and are exact: 0.1m + 0.2m = 0.3m. Convert with decimal quantity, and round with System.Math.Round(value, 2, System.MidpointRounding.AwayFromZero).

Common beginner mistakes

  • Commas in records. { Name = "Ada", Email = "a@x.com" } doesn't compile: the comma builds a tuple. Use ; or newlines.
  • TS-style : in values. { Name: "Ada" } is a type-annotation syntax error. Values use =.
  • Trying to mutate. ada.Name <- "Bob" fails: record fields are immutable. Use { ada with Name = "Bob" }.
  • Missing fields. Every field must be given when you create a record ("No assignment given for field 'IsVip'").
  • Two record types with the same field names. F# infers the most recently declared one. Annotate ((c: Customer)) or qualify a field ({ Customer.Name = "Ada"; ... }) when it guesses wrong.
  • fst on a triple. fst/snd only work on pairs. Destructure instead: let (a, _, _) = triple.
  • Tuple vs curried parameters. let area (w, h) = w * h takes one tuple, so it's called area (3, 4), not area 3 4.
  • Forgetting the self identifier. Members need it: member this.Total, not member Total.
  • Float for money. Use decimal (19.99m) and convert ints with decimal qty.

Cheat sheet

▶ Try
let t = (1, "a")                      // tuple: int * string
let (n, s) = t                        // destructure; fst t, snd t for pairs
type Person = { Name: string; Age: int }
let p = { Name = "Ada"; Age = 36 }    // create (type inferred from fields)
let older = { p with Age = 37 }       // copy-and-update
p = { Name = "Ada"; Age = 36 }        // true: structural equality
match p with
| { Age = age } when age >= 18 -> "adult"
| _ -> "minor"
let { Name = name } = p               // destructure a record
let anon = {| Id = 1; Tags = [ "x" ] |}   // anonymous record
type Money =
    { Amount: decimal; Currency: string }
    member this.IsZero = this.Amount = 0m
    static member Zero(currency: string) = { Amount = 0m; Currency = currency }

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app