An F# Records is similar to a tuple, however, it contains named fields. For example,
type website = { title : string; url : string }
Defining F# Records
A record is defined as a type using the type keyword, and the fields of the record are defined as a semicolon-separated list.
The syntax for defining a record is −
type recordName = { [ fieldName : dataType ] + }
Creating a Record
You can create a record by specifying the record’s fields. For example, let us create a website record named homepage −
let homepage = { Title = "Adglob Point"; Url = "www.adglob.in" }
The following examples will explain the concepts −
Example 1
This program defines a record type named website. Then it creates some records of type website and prints the records.
(* defining a record type named website *) type website = { Title : string; Url : string } (* creating some records *) let homepage = { Title = "Adglob Point"; Url = "www.adglob.in" } let cpage = { Title = "Learn C"; Url = "www.adglob.in/cprogramming/index.htm" } let fsharppage = { Title = "Learn F#"; Url = "www.adglob.in/fsharp/index.htm" } let csharppage = { Title = "Learn C#"; Url = "www.adglob.in/csharp/index.htm" } (*printing records *) (printfn "Home Page: Title: %A \n \t URL: %A") homepage.Title homepage.Url (printfn "C Page: Title: %A \n \t URL: %A") cpage.Title cpage.Url (printfn "F# Page: Title: %A \n \t URL: %A") fsharppage.Title fsharppage.Url (printfn "C# Page: Title: %A \n \t URL: %A") csharppage.Title csharppage.Url
When you compile and execute the program, it yields the following output −
Home Page: Title: "adglob Point" URL: "www.adglob.in" C Page: Title: "Learn C" URL: "www.adglob.in/cprogramming/index.htm" F# Page: Title: "Learn F#" URL: "www.adglob.in/fsharp/index.htm" C# Page: Title: "Learn C#" URL: "www.adglob.in/csharp/index.htm"
Example 2
type student = { Name : string; ID : int; RegistrationText : string; IsRegistered : bool } let getStudent name id = { Name = name; ID = id; RegistrationText = null; IsRegistered = false } let registerStudent st = { st with RegistrationText = "Registered"; IsRegistered = true } let printStudent msg st = printfn "%s: %A" msg st let main() = let preRegisteredStudent = getStudent "Zara" 10 let postRegisteredStudent = registerStudent preRegisteredStudent printStudent "Before Registration: " preRegisteredStudent printStudent "After Registration: " postRegisteredStudent main()
When you compile and execute the program, it yields the following output −
Before Registration: : {Name = "Zara"; ID = 10; RegistrationText = null; IsRegistered = false;} After Registration: : {Name = "Zara"; ID = 10; RegistrationText = "Registered"; IsRegistered = true;}
Next Topic – Click Here
Pingback: F# - Tuples - Adglob Infosystem Pvt Ltd