在FSI I型为什么FSharp交互允许mutable让?
> let a = 10;;
val a : int = 10
> let a = a + 1;;
val a : int = 11
看起来像我在这里有一个可变的变量?我错过了什么吗?
在FSI I型为什么FSharp交互允许mutable让?
> let a = 10;;
val a : int = 10
> let a = a + 1;;
val a : int = 11
看起来像我在这里有一个可变的变量?我错过了什么吗?
这不是一个可变值。但是你使用阴影:在F#中,当在特定范围(判定块,方法或内部类)中声明的变量与在外部范围中声明的变量名称相同时,会发生值阴影。
如果你想有一个可变值,有F#中syntaxe:
let mutable a = 10
a <- a + 1
由于已经由亚瑟,你看到的是阴影这意味着原来的“变量”命名a
解释被名为a
的新“变量”隐藏(我在引号中使用变量,因为它们实际上是不可变的值)。
要看到其中的差别,你可以在一个函数获取原始值,然后隐藏原始值后,打印出值:
> let a = 10;; // Define the original 'a' value
val a : int = 10
> let f() = a;; // A function captures the original value
val f : unit -> int
> let a = 42;; // Define a new value hiding the first 'a'
val a : int = 42
> f();; // Prints the original value - it is not mutated!
val it : int = 10
可悲的是,你不能使用完全相同的代码,看看如何let mutable
的行为(因为F#不允许捕捉封可变参考),但你可以看到突变,当您使用参考单元(也就是一个简单的对象,在堆存储可变值):
> let a = ref 10;; // Create a mutable reference cell initialized to 10
val a : int ref = {contents = 10;}
> let f() = !a;; // A function reads the current value of the cell
val f : unit -> int
> a := 42;; // Overwrite the value in the cell with 42
val it : unit =()
> f();; // Prints the new value - it is mutated
val it : int = 42
您可以在F#interactive中逐行运行代码,但是当您复制整个代码片段(输入行)并将它们放入正常的F#代码中时,它会执行完全相同的操作。在一个函数或模块中。 ;;
只是为了结束F#交互式输入(我在F#交互式窗口中键入代码)中的行,但它在普通代码中不需要,因为F#使用缩进找出语句结束的位置。
你能否在这里详细说明,因为它看起来像变量在相同的范围内进行了变异。注意''let a = a + 1'' – bradgonesurfing 2013-04-21 19:20:30
@bradgonesurfing:你只需要两个同名的(_different_)值。 – ildjarn 2013-04-21 19:30:58
好吧,我只是在FSI说服了自己。但是,这个FSI是用双冒号'';;''特定的还是总是这样工作的? – bradgonesurfing 2013-04-21 19:35:00