liveBook · Manning

Alter

As explained in Clojure: The Essential Reference

alter is a Clojure function that updates a ref inside a transaction by applying a function to its old value.

alter updates a ref inside a transaction by applying a function to its current value. Place it inside dosync when coordinating changes across multiple refs. section 14.4

Use alter when:

  • A function such as inc, +, or - computes the next ref value. section 14.4
  • Several refs must change atomically within one dosync transaction. section 14.4
  • Prefer ref-set when directly replacing a ref’s value instead of deriving it through a function. section 14.4

Coordinated account transfer

Define two refs and update them together: (dosync (alter account-1 - amount) (alter account-2 + amount)). Transferring 300 from accounts holding 1000 and 500 produces {:account-1 700, :account-2 800}.

How Clojure: The Essential Reference covers it

How deep it goes
Defines function-based ref updates and demonstrates atomic coordination, while deferring implementation internals.
Examples
Demonstrates a bank-account transfer using subtraction and addition functions applied to coordinated refs.
What it assumes
Assumes familiarity with Clojure functions and refs, then places alter within dosync-based STM coordination.
What you can do after
Apply it via dosync to build coordinated transactional updates over multiple refs.
How it connects
Connects alter with ref, dosync, commute, ensure, ref-set, and software transactional memory.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.