在F#中不可变 [英] immutable in F#

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

问题描述

我知道F#中的变量默认是不可变的. 但是,例如在F#交互式中:

I know that variables in F# are immutable by default. But, for example in F# interactive:

  > let x = 4;;

val x : int = 4

> let x = 5;;

val x : int = 5

> x;;
val it : int = 5
> 

因此,我将4分配给x,然后将5分配给x,并且它正在变化.这是正确的吗?它应该给出一些错误或警告吗?还是我不明白它是如何工作的?

So, I assign 4 to x, then 5 to x and it's changing. Is it correct? Should it give some error or warning? Or I just don't understand how it works?

推荐答案

编写let x = 3时,会将标识符x绑定到值3.如果您在同一范围内第二次执行此操作,则是在声明一个新的标识符,该标识符将隐藏先前的标识符,因为它具有相同的名称.

When you write let x = 3, you are binding the identifier x to the value 3. If you do that a second time in the same scope, you are declaring a new identifier that hides the previous one since it has the same name.

通过破坏性更新运算符<-完成F#中的值.对于不变值,这将失败:

Mutating a value in F# is done via the destructive update operator, <-. This will fail for immutable values, i.e.:

> let x = 3;;

val x : int = 3

> x <- 5;;

  x <- 5;;
  ^^^^^^

stdin(2,1): error FS0027: This value is not mutable

要声明可变变量,请在let之后添加mutable:

To declare a mutable variable, add mutable after let:

let mutable x = 5;;

val mutable x : int = 5

> x <- 6;;
val it : unit = ()
> x;;
val it : int = 6

您可能会问,两者之间有什么区别?一个例子可能就足够了:

But what's the difference between the two, you might ask? An example may be enough:

let i = 0;
while i < 10 do
    let i = i + 1
    ()

尽管出现,但这是一个无限循环.在循环内部声明的i是另一个i,它隐藏了外部的i.外部变量是不可变的,因此它始终保持其值0,并且循环永远不会结束.正确的写法是使用可变变量:

Despite the appearances, this is an infinite loop. The i declared inside the loop is a different i that hides the outer one. The outer one is immutable, so it always keeps its value 0 and the loop never ends. The correct way to write this is with a mutable variable:

let mutable i = 0;
while i < 10 do
    i <- i + 1
    ()

这篇关于在F#中不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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