f-sharp
  1. f-sharp-records

F# Records

In F#, records are a simple and lightweight way to define a data structure with named fields. In this page, we will cover the syntax, examples, output, explanation, use, important points, and summary of F# records.

Syntax

A record is defined using the type keyword followed by the record name, an equal sign, and a list of fields separated by semicolons. The syntax to define a record is as follows:

type person = { 
    name: string; 
    age: int;
    address: string;
}

Here, we have defined a record named person with three named fields: name, age, and address.

Example

Here's an example of creating a record instance in F#:

let person1 = { name = "John"; age = 28; address = "123 Main St" }

In this example, we have created a record instance person1 of type person with the name "John", age 28, and the address "123 Main St".

Output

To access the fields of a record, we use the dot notation. For example, to get the name of person1, we use the following code:

printfn "Name: %s" person1.name

The output of the above code will be:

Name: John

Explanation

Records provide a simple and easy way to define a data structure with named fields. The fields within a record can be accessed with the dot notation. Records are immutable by default, which means that the values of their fields cannot be changed once they are set. However, it's possible to create a new instance of a record with updated values for its fields.

Use

F# records are widely used in functional programming to represent data structures because of their simplicity and immutability. Records are commonly used to define domain objects and data transfer objects.

Important Points

  • F# records are defined using the type keyword followed by the record name and a list of fields separated by semicolons.
  • Records are immutable by default, which means that the values of their fields cannot be changed once they are set.
  • The fields of a record can be accessed with the dot notation.
  • Records are often used to define domain objects and data transfer objects.

Summary

In summary, F# records provide a lightweight and simple way to define a data structure with named fields. Records are immutable by default and can be used effectively to represent domain objects and data transfer objects.

Published on: