Skip to content
Records
step 1/5

Reading — step 1 of 5

Learn

~1 min readRecords and Collections

F# records are named-field tuples with structural equality. Like data classes in Kotlin or case classes in Scala.

type Person = {
    Name: string
    Age: int
}

let ada = { Name = "Ada"; Age = 36 }
let older = { ada with Age = 37 }       // copy with one field changed

printfn "%s is %d" ada.Name ada.Age
printfn "%A" ada                          // Person { Name = "Ada"; Age = 36 }

ada = { Name = "Ada"; Age = 36 }          // structural equality — true

Records are immutable by default. The with syntax creates a new record with one or more fields changed.

Pattern matching on records:

match person with
| { Age = a } when a < 18 -> "minor"
| { Name = "Admin" } -> "administrator"
| _ -> "normal"

Anonymous records for ad-hoc shapes:

let summary = {| Count = 5; Average = 3.14 |}
printfn "%d %f" summary.Count summary.Average

Field access is just dot notation. There's no boilerplate getter/setter.

Records also auto-implement comparison if all field types implement comparison — sortable for free.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Records — F# Intermediate