Variables & Pattern Matching

6.1 Variables

Start with an uppercase letter or _: X, Name, _Ignored.

Single assignment: once bound, a variable can't change within its scope.

1> X = 5.
5
2> X = 6.
** exception error: no match of right hand side value 6
3> X = 5.        % succeeds: this is a match, not an assignment
5

6.2 = is the match operator

{ok, Value} = {ok, 42},              % Value = 42
[First, Second | Rest] = [1, 2, 3, 4],
{person, Name, _} = {person, "Ann", 30},
#{name := N} = #{name => "Bob", age => 25},
<<A:8, B:8, Tail/binary>> = <<1, 2, 3, 4>>.

6.3 Anonymous variable _

Matches anything, never binds. _Name documents intent while also not warning when unused (but it *does* bind).

6.4 Pattern matching on the same variable twice

{X, X} = {1, 1},     % OK
{Y, Y} = {1, 2}.     % badmatch

6.5 Immutability

All data is immutable. "Updating" creates a new value; unchanged parts are shared.