F#記錄

2018-12-15 13:42 更新

記錄類似于一個(gè)元組,但它包含命名字段。 例如,

type website =
   { title : string;
      url : string }

定義記錄

一個(gè)記錄被定義為使用type關(guān)鍵字類型,記錄的字段被定義為一個(gè)分號(hào)分隔的列表。

語(yǔ)法定義一個(gè)記錄 

type recordName =
   { [ fieldName : dataType ] + }

創(chuàng)建記錄

您可以通過(guò)指定記錄的字段創(chuàng)建一個(gè)記錄。例如,讓我們創(chuàng)建一個(gè)網(wǎng)站記錄中名為homepage

let homepage = { Title = "TutorialsPoint"; Url = "m.hgci.cn" }

下面的實(shí)例將解釋其中的概念 

例1

此程序定義一個(gè)名為website的記錄類型。 然后它創(chuàng)建一些類型的website記錄并打印記錄。

(* defining a record type named website *)
type website =
   { Title : string;
      Url : string }

(* creating some records *)
let homepage = { Title = "TutorialsPoint"; Url = "m.hgci.cn" }
let cpage = { Title = "Learn C"; Url = "m.hgci.cn/c/index.htm" }
let fsharppage = { Title = "Learn F#"; Url = "m.hgci.cn/fsharp/index.htm" }
let csharppage = { Title = "Learn C#"; Url = "m.hgci.cn/csharp/index.htm" }

(*printing records *)
(printfn "Home Page: Title: %A 
 	 URL: %A") homepage.Title homepage.Url
(printfn "C Page: Title: %A 
 	 URL: %A") cpage.Title cpage.Url
(printfn "F# Page: Title: %A 
 	 URL: %A") fsharppage.Title fsharppage.Url
(printfn "C# Page: Title: %A 
 	 URL: %A") csharppage.Title csharppage.Url

當(dāng)你編譯和執(zhí)行程序,它產(chǎn)生以下輸出 

Home Page: Title: "TutorialsPoint"
       URL: "m.hgci.cn"
C Page: Title: "Learn C"
      URL: "m.hgci.cn/c/index.htm"
F# Page: Title: "Learn F#"
      URL: "m.hgci.cn/fsharp/index.htm"
C# Page: Title: "Learn C#"
      URL: "m.hgci.cn/csharp/index.htm"

例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()

當(dāng)你編譯和執(zhí)行程序,它產(chǎn)生以下輸出 

Before Registration: : {Name = "Zara";
   ID = 10;
   RegistrationText = null;
   IsRegistered = false;}
After Registration: : {Name = "Zara";
   ID = 10;
   RegistrationText = "Registered";
   IsRegistered = true;}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)