liveBook · Manning

Mutable variable

As explained in F# in Action: A Revised Edition of Get Programming with F#

The mutable modifier declares that a field or binding may be changed after initialization.

A mutable variable is a binding or record field that may change after initialization. In F#, add mutable to the binding and use <- for assignment; = remains the equality operator. section 4.2.3 section 5.3.2

Use mutable state deliberately:

  • Prefer immutable values when a changing value can instead be represented by a sequence of new states. section 4.2.3
  • Choose mutable state when repeated updates are central, such as a record field changed thousands of times in a tight loop. section 5.3.2
  • Treat mutation as an optimization to test for, not the default; other bottlenecks, such as database queries, may matter more. section 5.3.2

Track a car’s gas tank

A mutable model keeps one gas value and updates it as the car drives: far halves the tank, medium removes 10, and near removes 1. Calling drive changes the shared gas value. The immutable alternative passes the current gas value into drive and returns the next state, making each transition explicit.

let name = "isaac"     #1
let mutable age = 42   #2
age <- 43              #3
if age = 43 then ...   #4

Compare F# syntax for immutable bindings, mutable bindings, assignment, and equality. section 4.2.3

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Defines declaration and assignment syntax, contrasts immutable state, and demonstrates a stateful gas-tank workflow.
Examples
Uses F# bindings, a mutable gas tank, drive calls, and an immutable sequence of gas states.
What it assumes
Assumes basic bindings and conditionals while contrasting assignment with equality and immutable value flow.
What you can do after
Build it from scratch by declaring mutable bindings, updating them with <-, and comparing them with =.
How it connects
Connects mutable variables with immutable data, assignment, equality comparison, records, and state transitions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.