liveBook · Manning

Assignment

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

An assignment is an operation that binds or updates a variable with the result of an expression.

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

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

How deep it goes
Contrasts repeated branch assignment with expression results, then demonstrates mutable and immutable state updates.
Examples
Uses age descriptions and a car gas-tank simulation to compare direct updates with returned states.
What it assumes
Introduces F# mutable declarations and <- while contrasting familiar C# assignment and comparison syntax.
What you can do after
Apply it via F# syntax by declaring mutable state and updating it with <- when direct mutation is needed.
How it connects
Connects assignment with expressions, mutable data, immutable data, equality comparison, and state.

Also explained in

Compare how 7 books explain assignment →

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.