a record is similar to a tuple, however it contains named fields. for example,
type website =
{ title : string;
url : string }
defining record
a record is defined as a type using the type keyword, and the fields of the record are defined as a semicolon-separated list.
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 = "tutorialspoint"; url = "www.tutorialspoint.com" }
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 = "tutorialspoint"; url = "www.tutorialspoint.com" }
let cpage = { title = "learn c"; url = "www.tutorialspoint.com/cprogramming/index.htm" }
let fsharppage = { title = "learn f#"; url = "www.tutorialspoint.com/fsharp/index.htm" }
let csharppage = { title = "learn c#"; url = "www.tutorialspoint.com/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: "tutorialspoint"
url: "www.tutorialspoint.com"
c page: title: "learn c"
url: "www.tutorialspoint.com/cprogramming/index.htm"
f# page: title: "learn f#"
url: "www.tutorialspoint.com/fsharp/index.htm"
c# page: title: "learn c#"
url: "www.tutorialspoint.com/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;}