Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Types, Records and Unions

Records and Anonymous Records

Learn F# records: declaring fields, creating values, copy-and-update with with, structural equality, struct records, anonymous records and when to choose them over tuples or classes.

Most programs move around bundles of named data: a customer, an order line, a point on a map. In F# the everyday way to model such a bundle is the record. A record is a small, immutable type with named fields, and the compiler gives it equality, comparison, printing and pattern matching for free. You will write records far more often than classes.

This lesson shows how to declare and create records, how to "change" one with copy-and-update, how equality works, and when an anonymous record or a struct record is the better fit.

F# does not run in the in-page editor on this site, so F# snippets are read-only and show the output only where it is certain. Where a runnable demo helps, we add a small C# stand-in that behaves the same way and say so.

Declaring and creating a record

FSHARP
type Person =
    { Name: string
      Age: int }

let ada = { Name = "Ada"; Age = 36 }
printfn "%A" ada

The compiler infers the type from the field names, so { Name = "Ada"; Age = 36 } is a Person. The %A format prints the value in a readable structural form:

TEXT
{ Name = "Ada"
  Age = 36 }

Fields are accessed with a dot: ada.Name. Every field must be given a value when you create the record, so there is no half-built Person and no null field by accident. If two record types share field names, the most recently declared type wins during inference, and you can disambiguate with an annotation (let p : Person = ...) or by qualifying a field ({ Person.Name = "Ada"; Age = 36 }).

Copy and update

Record fields are immutable by default. To get a changed version, you copy the record with the with keyword:

FSHARP
let older = { ada with Age = ada.Age + 1 }
// ada is unchanged; older = { Name = "Ada"; Age = 37 }

Only the listed fields differ, and everything else is copied. This is the F# answer to "how do I update something?" when nothing may be mutated. It also makes code easy to reason about: after let older = ..., nobody else holding ada sees a surprise. The idea pairs naturally with the pipeline style from Functions and Pipelines, where each step returns a new value.

C# C# stand-in: a record with copy-and-update

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.

Structural equality and comparison

Two records are equal when all their fields are equal. There is no reference check involved:

FSHARP
let a = { Name = "Ada"; Age = 36 }
let b = { Name = "Ada"; Age = 36 }
printfn "%b" (a = b)       // true
printfn "%b" (a <> older)  // true

Records are also comparable, field by field in declaration order, so you can sort them or use them as keys of a Map or members of a Set without extra code. If a field's type does not support equality (a function, for example), the record loses it too, and you get a compile-time error instead of a silent bug.

If you want reference semantics for one type, add [<ReferenceEquality>]. If you want to switch off structural equality or comparison, use [<NoEquality>] or [<NoComparison>]. Both are rare.

Methods, members and defaults

Records can carry members. These are ordinary functions attached to the type:

FSHARP
type Rectangle =
    { Width: float
      Height: float }
    member this.Area = this.Width * this.Height
    static member Square(side: float) = { Width = side; Height = side }

let r = Rectangle.Square 3.0
printfn "%f" r.Area   // 9.000000

There are no default values in a record declaration. A common pattern is a named "empty" value, and then copy-and-update from it:

FSHARP
module Person =
    let empty = { Name = ""; Age = 0 }

let newcomer = { Person.empty with Name = "Grace" }

Pattern matching on records

Records work directly in patterns, so you can pick fields out in a match:

FSHARP
let describe p =
    match p with
    | { Age = a } when a < 18 -> "minor"
    | { Name = "Ada" } -> "the countess"
    | _ -> "adult"

A pattern only needs to name the fields it cares about. See Pattern Matching in Depth for guards, nesting and exhaustiveness.

Struct records

By default a record is a reference type allocated on the heap. For small values created in huge numbers, put [<Struct>] in front to make it a value type:

FSHARP
[<Struct>]
type Point = { X: float; Y: float }

A struct record is copied on assignment and avoids a heap allocation, which can help in tight loops. Measure before you reach for it; a normal record is the right default.

Anonymous records

Sometimes you need a quick named bundle that is not worth a type declaration, for example the shape of one query result. An anonymous record uses {| ... |}:

FSHARP
let summary = {| Name = "Ada"; Total = 3 |}
printfn "%s has %d items" summary.Name summary.Total

let moved = {| summary with Total = 4 |}

Anonymous records are structural: two values with the same field names and types are the same type, even in different files. They are ideal for local data, JSON-like results and projections. Because they have no name, avoid putting them in long-lived public APIs: a named record documents intent better and gives clearer error messages. You can make one a struct with the struct keyword in front: struct {| X = 1; Y = 2 |}.

C# C# stand-in: anonymous types for quick projections

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.

Records, tuples or classes?

flowchart TD
    A["Need to group values?"] --> B{"Used in one<br/>small place?"}
    B -->|"yes, positions are clear"| C["Tuple"]
    B -->|"yes, names help"| D["Anonymous record"]
    B -->|"no, shared by many functions"| E{"Needs identity<br/>or mutable state?"}
    E -->|"no"| F["Record"]
    E -->|"yes"| G["Class"]

A quick guide: reach for a named record when data is shared, and a class only when identity or hidden mutable state matters.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does { ada with Age = 37 } produce?

    Copy-and-update never mutates. It builds a new record and copies every field that you did not list.
  2. 2. How does F# decide whether two records are equal?

    Records get structural equality and comparison automatically. Reference equality needs an explicit attribute.
  3. 3. Which syntax declares an anonymous record?

    Anonymous records are written with the {| and |} brackets and need no type declaration.
  4. 4. When is [<Struct>] on a record worth considering?

    Struct records avoid heap allocations but are copied on assignment, so they suit small values in hot paths.

Summary

  • A record is an immutable bundle of named fields with free equality, comparison and printing.
  • Create records with { Field = value } and change them with { r with Field = value }.
  • Records can have members and work in patterns; there are no field defaults, so define an "empty" value.
  • [<Struct>] makes a value-type record; {| ... |} makes an anonymous record for local data.
  • Use named records for shared data and classes only for identity or hidden mutable state.

Next: Discriminated Unions