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'
例如,
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ù)的結(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";}
更多建議: