F#中的阴影与设置值 [英] Shadowing vs. Setting value in F#

查看:105
本文介绍了F#中的阴影与设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经介绍过,默认情况下,数据在F#中是不可变的.当我们将值重新分配给某个变量时,实际上发生的是它重新绑定了变量的值,但是设置新值却是另一回事. 重新绑定称为阴影",而如果我们不明确地说变量的值是可变的,则不可能设置新值.

I've been introduced that data, by default is immutable in F#. When we reassign value to some variable, what really happens is that it rebinds the value of variable, but setting a new value is different thing. Rebinding is called Shadowing whilst setting new value is impossible if we explicitly don't say that value of the variable is mutable.

有人可以详细解释这个概念吗?重影(重新绑定)之间有什么区别

Can anybody explain me this concept in details? what's difference between shadowing (rebinding) by

let var = "new_value"

并设置新值,例如

var <- "new_value"

这是一会儿,在重新绑定期间我们创建另一个对象,然后将该对象的地址分配给变量,而在第二个示例中,我们更改了值本身吗?我从对内存的堆/栈理解中带来了这一点.我可能是错的.

Is this a moment, that during rebinding we create another object and we assign that object's address to variable whereas in the second example we change the value itself? I brought that from heap/stack understanding of memory.. I may be wrong.

谢谢

推荐答案

阴影是在创建使用与先前绑定相同名称的 new 绑定时.这会遮盖"原始名称,将其隐藏但不会更改或替换.在FSI中尝试此操作以查看:

Shadowing is when you create a new binding that uses the same name as a previous binding. This "shadows" the original name, which hides it but doesn't change or replace it. Try this in FSI to see:

let foo = 42

let printFoo () = 
    printfn "%i" foo 

printFoo() ;;

这将打印:

42

val foo : int = 42
val printFoo : unit -> unit
val it : unit = ()

然后添加:

// ... more code
let foo = 24

printfn "%i" foo // prints 24
printFoo ();;

这将打印:

24
42

val foo : int = 24
val it : unit = ()

请注意,当您调用printFoo()时,它仍然会打印42-该函数会看到原始(未阴影)的绑定,但是新的打印会显示新的值.

Note that it still prints 42 when you call printFoo() - the function sees the original (unshadowed) binding, but the new print shows the new value.

使用<-突变值需要可变的绑定:

Using <- to mutate a value requires a mutable binding:

let mutable bar = 42

let printBar () = 
    printfn "%i" bar

printBar ();;

这与上面一样,显示为42.请注意,此处使用mutable关键字覆盖了默认的不可变行为.

This, like above, prints 42. Note that you override the default immutable behavior here with the mutable keyword.

然后在可变绑定内更改值:

You then change the value within the mutable binding:

bar <- 24
printfn "%i" bar
printBar ();;

这将打印两次24,因为与阴影版本不同,该突变会更改原始绑定.如果您在原始绑定中不使用mutable,则在使用<-时会收到错误消息.

This will print 24 twice, since, unlike the shadowed version, the mutation changes the original binding. If you leave mutable off in the original binding, you'll get an error when using <-.

这篇关于F#中的阴影与设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆