liveBook · Manning

Immutable collection

As explained in Elixir in Action, Third Edition

Immutable data is data whose value cannot be changed after it has been created, so modifications produce new versions instead of altering existing values.

Immutability means data cannot be changed after creation. Transformations return new values, while existing values remain available. Elixir variables may be rebound, but rebinding points the name elsewhere rather than modifying stored data. section 2.2 section 2.8

Immutability shapes both implementation and program structure:

  • Functions can behave as side-effect-free transformations with explicit inputs and outputs, making them easier to analyze, understand, test, and compose. section 2.4.5
  • Pipelines pass each transformed value to the next function, avoiding temporary variables while preserving the immutable data flow. section 1.2.2
  • Updated structures share as much memory as possible with earlier versions; changing a tuple creates a shallow copy, while pushing onto a list reuses its tail. section 2.4.5
  • Deep updates transform the target, its containing collection, and each ancestor rather than modifying a nested value in place. section 4.2.3

Transforming a nested map

A to-do entry can be changed with put_in(todo_list[3].title, "Theater"). The operation returns a new to-do list and leaves the original structure intact; the result must be assigned if it is to be used later. section 4.2.3

iex(2)> put_in(todo_list[3].title, "Theater")       #1
 
%{
  1 => %{date: ~D[2023-12-19], title: "Dentist"},
  2 => %{date: ~D[2023-12-20], title: "Shopping"},
  3 => %{date: ~D[2023-12-19], title: "Theater"}    #2
}

Inspect a concrete nested-map update that preserves the original value while returning a changed version. section 4.2.3

How Elixir in Action, Third Edition covers it

How deep it goes
Explains rebinding, side effects, structural sharing, list and tuple costs, and recursive hierarchical updates without descending into runtime implementation.
Examples
Demonstrates tuple replacement, list construction, pipelined transformations, and nested to-do-list updates with put_in.
What it assumes
Assumes basic Elixir variables, functions, collections, and expressions while teaching the distinction between variable rebinding and data mutation.
What you can do after
Apply it via Elixir transformations, pipelines, rebinding, and put_in updates while retaining earlier data versions.
How it connects
Connects functional programming, side effects, higher-order functions, pipe operators, structural sharing, garbage collection, and hierarchical data structures.

Also explained in

Compare how 24 books explain immutable collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.