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
