- F# 基础教程
- F# - 首页
- F# - 概述
- F# - 环境设置
- F# - 程序结构
- F# - 基本语法
- F# - 数据类型
- F# - 变量
- F# - 运算符
- F# - 决策
- F# - 循环
- F# - 函数
- F# - 字符串
- F# - 可选值 (Options)
- F# - 元组
- F# - 记录
- F# - 列表
- F# - 序列
- F# - 集合
- F# - 映射
- F# - discriminated union (判别联合)
- F# - 可变数据
- F# - 数组
- F# - 可变列表
- F# - 可变字典
- F# - 基本I/O
- F# - 泛型
- F# - 委托
- F# - 枚举
- F# - 模式匹配
- F# - 异常处理
- F# - 类
- F# - 结构体
- F# - 运算符重载
- F# - 继承
- F# - 接口
- F# - 事件
- F# - 模块
- F# - 命名空间
F# - 可变数据
F# 中的变量是不可变的,这意味着一旦变量绑定到一个值,就不能更改。它们实际上编译为静态只读属性。
下面的例子演示了这一点。
示例
let x = 10 let y = 20 let z = x + y printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z let x = 15 let y = 20 let z = x + y printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z
编译并执行程序时,会显示以下错误消息:
Duplicate definition of value 'x' Duplicate definition of value 'Y' Duplicate definition of value 'Z'
可变变量
有时需要更改存储在变量中的值。为了指定在程序的后面部分可以更改已声明和赋值变量的值,F# 提供了mutable关键字。可以使用此关键字声明和赋值可变变量,其值将发生更改。
mutable关键字允许你声明和赋值可变变量的值。
可以使用let关键字为可变变量赋值初始值。但是,要为其赋值新的后续值,需要使用<-运算符。
例如:
let mutable x = 10 x <- 15
下面的例子将阐明这个概念:
示例
let mutable x = 10 let y = 20 let mutable z = x + y printfn "Original Values:" printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z printfn "Let us change the value of x" printfn "Value of z will change too." x <- 15 z <- x + y printfn "New Values:" printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z
编译并执行程序时,将产生以下输出:
Original Values: x: 10 y: 20 z: 30 Let us change the value of x Value of z will change too. New Values: x: 15 y: 20 z: 35
可变数据的用途
可变数据经常在数据处理中需要并使用,尤其是在记录数据结构中。下面的例子演示了这一点:
open System
type studentData =
{ ID : int;
mutable IsRegistered : bool;
mutable RegisteredText : string; }
let getStudent id =
{ ID = id;
IsRegistered = false;
RegisteredText = null; }
let registerStudents (students : studentData list) =
students |> List.iter(fun st ->
st.IsRegistered <- true
st.RegisteredText <- sprintf "Registered %s" (DateTime.Now.ToString("hh:mm:ss"))
Threading.Thread.Sleep(1000) (* Putting thread to sleep for 1 second to simulate processing overhead. *))
let printData (students : studentData list) =
students |> List.iter (fun x -> printfn "%A" x)
let main() =
let students = List.init 3 getStudent
printfn "Before Process:"
printData students
printfn "After process:"
registerStudents students
printData students
Console.ReadKey(true) |> ignore
main()
编译并执行程序时,将产生以下输出:
Before Process:
{ID = 0;
IsRegistered = false;
RegisteredText = null;}
{ID = 1;
IsRegistered = false;
RegisteredText = null;}
{ID = 2;
IsRegistered = false;
RegisteredText = null;}
After process:
{ID = 0;
IsRegistered = true;
RegisteredText = "Registered 05:39:15";}
{ID = 1;
IsRegistered = true;
RegisteredText = "Registered 05:39:16";}
{ID = 2;
IsRegistered = true;
RegisteredText = "Registered 05:39:17";}
广告