Records
优质
小牛编辑
131浏览
2023-12-01
record类似于元组,但它包含命名字段。 例如,
type website =
{ title : string;
url : string }
定义记录
记录定义为使用type关键字的type ,记录的字段定义为以分号分隔的列表。
定义记录的语法是 -
type recordName =
{ [ fieldName : dataType ] + }
创建记录
您可以通过指定记录的字段来创建记录。 例如,让我们创建一个名为homepage的website记录 -
let homepage = { Title = "IoWiki"; Url = "www.iowiki.com" }
以下示例将解释这些概念 -
例子1 (Example 1)
该程序定义了一个名为网站的记录类型。 然后它创建一些类型网站的记录并打印记录。
(* defining a record type named website *)
type website =
{ Title : string;
Url : string }
(* creating some records *)
let homepage = { Title = "IoWiki"; Url = "www.iowiki.com" }
let cpage = { Title = "Learn C"; Url = "www.iowiki.com/cprogramming/index.htm" }
let fsharppage = { Title = "Learn F#"; Url = "www.iowiki.com/fsharp/index.htm" }
let csharppage = { Title = "Learn C#"; Url = "www.iowiki.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
编译并执行程序时,它会产生以下输出 -
Home Page: Title: "IoWiki"
URL: "www.iowiki.com"
C Page: Title: "Learn C"
URL: "www.iowiki.com/cprogramming/index.htm"
F# Page: Title: "Learn F#"
URL: "www.iowiki.com/fsharp/index.htm"
C# Page: Title: "Learn C#"
URL: "www.iowiki.com/csharp/index.htm"
例子2 (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()
编译并执行程序时,它会产生以下输出 -
Before Registration: : {Name = "Zara";
ID = 10;
RegistrationText = null;
IsRegistered = false;}
After Registration: : {Name = "Zara";
ID = 10;
RegistrationText = "Registered";
IsRegistered = true;}