F#中的变量不可变,这意味着一旦变量绑定到某个值,就无法更改.它们实际上被编译为静态只读属性.
以下示例演示了这一点.
示例
let x = 10let y = 20let z = x + yprintfn "x: %i" xprintfn "y: %i" yprintfn "z: %i" zlet x = 15let y = 20let z = x + yprintfn "x: %i" xprintfn "y: %i" yprintfn "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 = 10x <- 15
以下示例将清除概念 :
示例
let mutable x = 10let y = 20let mutable z = x + yprintfn "Original Values:"printfn "x: %i" xprintfn "y: %i" yprintfn "z: %i" zprintfn "Let us change the value of x"printfn "Value of z will change too."x <- 15z <- x + yprintfn "New Values:"printfn "x: %i" xprintfn "y: %i" yprintfn "z: %i" z
当您编译并执行程序时,它会产生以下输出 :
Original Values:x: 10y: 20z: 30Let us change the value of xValue of z will change too.New Values:x: 15y: 20z: 355
可变数据的使用
通常需要可变数据并用于数据处理,尤其是记录数据结构.以下示例演示了此 :
open Systemtype 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) |> ignoremain()
编译并执行程序时,它会产生以下输出 :
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";}