You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
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 ...

The best content for your career. Discover unlimited learning on demand for around $1/day.