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























