Making variables mutable in F#
June 25, 2017 Leave a comment
F# takes immutability of variables very seriously. If a variable is declared with the let keyword then it is also immutable, meaning we can’t change its value after the declaration. In many popular OOP languages immutability only concerns strings but in F# all types are covered.
Here’s an immutable integer:
let thisIsImmutable = 3
Trying to assign a new value will fail:
thisIsImmutable <- thisIsImmutable + 1
The compiler will complain with the following message:
This value is not mutable
F# nevertheless has support for mutable variables but we need to state our intention explicitly using the “mutable” keyword:
let mutable thisIsMutable = 3 thisIsMutable <- thisIsMutable + 10
The compiler will stop complaining.
View all F# related articles here.