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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.