Assignment stores an expression result in a variable or updates a mutable variable. Keeping assignment in one clear location separates calculating a value from storing it, which makes branch-heavy code easier for both people and the compiler to reason about. section 4.1.3 section 4.2.3
Prefer a structure that makes updates explicit:
- Compute a value with an expression, then assign its result once. This avoids default placeholder values and prevents different branches from updating the wrong variable. section 4.1.3
- In F#, create an immutable value with let; declare let mutable only when later updates are required. section 4.2.3
- Use <- to mutate an F# variable. Use = for equality comparison, unlike C# where = assigns and == compares. section 4.2.3
Updating a gas tank
A mutable simulation changes shared state directly: let mutable gas = 100.0 let drive distance = if distance = "far" then gas <- gas / 2.0 elif distance = "medium" then gas <- gas - 10.0 else gas <- gas - 1.0 An immutable alternative passes the current gas level in and returns the next level. Each named state then records the result of one drive. section 4.2.3
Listing 4.7 Managing state with immutable values
let drive gas distance = #1
if distance = "far" then gas / 2.0
elif distance = "medium" then gas – 10.0
else gas – 1.0
let gas = 100.0 #2
let firstState = drive gas "far" #3
let secondState = drive firstState "medium"
let finalState = drive secondState "near" #4
Compare returned state values with direct mutation: each drive call consumes a gas value and produces the next one. section 4.2.3






