F#的可變數(shù)據(jù)

2018-12-15 16:39 更新

F#中的變量是不可變的,這意味著一旦變量綁定到一個值,它就不能被改變。 它們實際上被編譯為靜態(tài)只讀屬性。

下面的例子說明了這一點。

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

當(dāng)你編譯和執(zhí)行程序,它顯示了以下錯誤消息 

Duplicate definition of value 'x'
Duplicate definition of value 'Y'
Duplicate definition of value 'Z'

可變變量

有時您需要更改存儲在變量中的值。 要指定在程序的后面部分中聲明的和分配的變量的值可能有變化,F(xiàn)#提供mutable。 您可以使用此關(guān)鍵字聲明和分配可變變量,其值將更改。
mutable允許在可變變量中聲明和賦值。
您可以使用theletkeyword為可變變量分配一些初始值。 但是,要為其分配新的后續(xù)值,需要使用<-運算符。

例如,

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

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

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

可變數(shù)據(jù)的使用

可變數(shù)據(jù)通常需要和在數(shù)據(jù)處理中使用,特別是與記錄數(shù)據(jù)的結(jié)構(gòu)。下面的例子說明了這一點 

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

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

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";}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號