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
>
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?
When you write
let x = 3, you are binding the identifierxto the value3. 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.Mutating a value in F# is done via the destructive update operator,
<-. This will fail for immutable values, i.e.:To declare a mutable variable, add
mutableafterlet:But what’s the difference between the two, you might ask? An example may be enough:
Despite the appearances, this is an infinite loop. The
ideclared inside the loop is a differentithat hides the outer one. The outer one is immutable, so it always keeps its value0and the loop never ends. The correct way to write this is with a mutable variable: