Cover by Chris Smith

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Records

Discriminated unions are great for defining a hierarchy of data, but when you are trying to get values out of a discriminated union they have the same problem as tuples, namely, that there is no meaning associated with each value—rather, data is lumped together in some fixed ordering. For example, consider a single-case discriminated union for describing a person. Are its two string fields referring to the first and then last name, or the last and then first name? This can lead to confusion and bugs down the road.

type Person =
    | Person of string * string * int

let steve = Person("Steve", "Holt", 17)
let gob = Person("Bluth", "George Oscar", 36)

When you want to group your data into a structured format without needing hefty syntax, you can use the F# record type. Records give you a way to organize values into a type, as well as name those values through fields.

To define a record, you simply define a series of name/type pairs enclosed in curly braces. To create an instance of a record, simply provide a value for each record field and type inference will figure out the rest. See Example 3-8.

Example 3-8. Constructing and using records

> // Define a record type
type PersonRec = { First : string; Last : string; Age : int};;

type PersonRec =
  {First: string;
   Last: string;
   Age: int;}

> // Construct a record
let steve = { First = "Steve"; Last = "Holt"; Age = 17 };; val steve : PersonRec = {First = "Steve"; Last = "Holt"; Age = 17;} > // Use '.field' to access record fields printfn ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required