Once a variable is defined to have a particular value, it keeps that value indefinitely. There are exceptions to this, and shadowing can be used to override a previous assignment made within the same scope. Thus, variables in mathematics are immutable. Similarly, variables in F# are immutable with some exceptions.
Immutable variables are default in F#. They are useful because they are thread-safe and easier to reason about. This is one of the reasons you may have heard a lot about immutability recently. The concept is to solve the biggest issues and design flaws of concurrent programming, including shared mutable state. If the values do not change, there is no need to protect them either, which is one of the reasons for promoting immutability in concurrent programming.
If you try to alter the value of an immutable variable, you will encounter a message similar to the following:
let immutable = "I am immutable!" immutable <- "Try to change it..." … error FS0027: This value is not mutable
Sometimes, however, it's desirable to have variables that are mutable. Often the need arises in real-life applications when some global state is shared like a counter. Also, object-oriented programming and interoperability with other .NET languages makes the use of mutability unavoidable.
To create a mutable variable, you simply put the keyword mutable
in front of the name as shown in the following line of code:
let mutable name = firstname + lastname
To change the variable, after it is created, use the arrow operator (←
) as shown in the following line of code:
name ← "John Johnson"
This is a little bit different from other languages. But once you have wrapped your head around the concept, it makes more sense. In fact, it will most likely be one of the main ways to reason about variables in the future as well.