Making variables mutable in F#

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.

Unknown's avatarAbout Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.