Saturday, February 18, 2017

What are mutable and immutable variables in F#?

If I assign a value to a variable and then later in the program I assign another value to the same varible the program does not care if it is a mutable variable. However if it is immutable, the program does not accept it. Hence immutable variable is one which is solidly bound to its value.

Let me take you to the .NET Fiddle site so that you can run it yourself and see the result.

First of all assignment to a variable in F# has the following syntax:

let x=25
 
The above statement assigns a value 25 to the variable x. I can print it to the screen using the second statement (printfn "x: %i" x) because x is an integer.






Next I assign a value of 45. You can see the error in this statement immediately. Hence value of x is immutable.


Now how can I assign a mutable value?

Well, F# uses the keyword mutable as shown here:

let mutable x=15

Now x has a value which can be changed later as shown in the next image. The first statement sets a value 15 for the variable x and the second statement prints it.

The third statement assigns a new value to it, namely 20 and the fourth line prints it. Observe carefully the new value assignment, a backward going arrow.





No comments: