Immutability Drives Everything
You’ve probably heard that functional programming means that the same inputs will give you the same outputs. You’ve likely also heard that Elixir binds variables exactly once.
When we say Elixir doesn’t allow mutable variables, you might be tempted to push back. Technically, you’d be right, but we should show you the games the compiler is playing to maintain the illusion of mutability. Take a look at this example:
| iex> x = 10 |
| 10 |
| iex> x |
| 10 |
| iex> x = 11 |
| 11 |
| iex> x |
| 11 |
That looks like x is mutable, but what you’re seeing is not the full picture. The values 10 and 11 are immutable. x is a variable that can be rebound at will within the scope of a function. Look at this second example:
| iex> x = 10 |
|
Get Designing Elixir Systems With OTP now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.