- F# 基础教程
- F# - 主页
- F# - 概述
- F# - 环境设置
- F# - 程序结构
- F# - 基本语法
- F# - 数据类型
- F# - 变量
- F# - 运算符
- F# - 决策
- F# - 循环
- F# - 函数
- F# - 字符串
- F# - 选项
- F# - 元组
- F# - 记录
- F# - 列表
- F# - 序列
- F# - 集
- F# - 地图
- F# - 受歧视的工会
- F# - 可变数据
- F# - 数组
- F# - 可变列表
- F# - 可变字典
- F# - 基本 I/O
- F# - 泛型
- F# - 代表
- F# - 枚举
- F# - 模式匹配
- F# - 异常处理
- F# - 类
- F# - 结构
- F# - 运算符重载
- F# - 继承
- F# - 接口
- F# - 事件
- F# - 模块
- F# - 命名空间
- F# 有用资源
- F# - 快速指南
- F# - 有用的资源
- F# - 讨论
F# - 记录
记录类似于元组,但它包含命名字段。例如,
type website = { title : string; url : string }
定义记录
使用type关键字将记录定义为类型,并将记录的字段定义为以分号分隔的列表。
定义记录的语法是 -
type recordName = { [ fieldName : dataType ] + }
创建记录
您可以通过指定记录的字段来创建记录。例如,让我们创建一个名为homepage的网站记录-
let homepage = { Title = "TutorialsPoint"; Url = "www.tutorialspoint.com" }
以下示例将解释这些概念 -
实施例1
该程序定义了一个名为 website 的记录类型。然后它创建一些网站类型的记录并打印这些记录。
(* 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
当您编译并执行该程序时,它会产生以下输出 -
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"
实施例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;}