F# - 可变变量(Mutable)

F# - 可变变量(Mutable) 首页 / F#入门教程 / F# - 可变变量(Mutable)

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 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

编译并执行程序时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/fsharp-mutable-data.html

来源:LearnFk无涯教程网

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

编译并执行程序时,将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/fsharp-mutable-data.html

来源:LearnFk无涯教程网

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";}

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

数据结构与算法之美 -〔王争〕

从0开始学大数据 -〔李智慧〕

Web协议详解与抓包实战 -〔陶辉〕

DDD实战课 -〔欧创新〕

摄影入门课 -〔小麥〕

罗剑锋的C++实战笔记 -〔罗剑锋〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

网络排查案例课 -〔杨胜辉〕

自动化测试高手课 -〔柳胜〕

好记忆不如烂笔头。留下您的足迹吧 :)