Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Language Basics

Variables and Single Assignment

Understand why Erlang variables bind only once, how the = sign is a pattern match rather than assignment, and how to use underscore and scope safely.

If you come from Python, Java or JavaScript, Erlang variables will feel strange at first. A variable here is bound to a value exactly once and never changes afterwards. This rule is not a limitation to work around. It is a major reason Erlang code is easy to reason about and safe to run in parallel.

Naming rules

A variable name starts with an uppercase letter or an underscore. The rest may contain letters, digits and underscores:

ERLANG
X
Name
UserCount
_unused
Total_2

By convention Erlang programmers write names in CamelCase: MaxRetries, not max_retries. Lowercase words are atoms, so total = 5 is not a variable assignment; it tries to match the atom total against 5 and fails.

Binding once

Before it is bound, a variable is called unbound. The first = binds it:

ERLANG
1> Age = 30.
30
2> Age.
30
3> Age = 31.
** exception error: no match of right hand side value 31

The third line does not "change Age". The = operator is not assignment. It is the match operator: it compares the right side with the left side and, if the left side contains unbound variables, binds them so the two sides become equal. Here Age is already 30, so the match 30 = 31 fails and raises a badmatch error.

Matching the same value again is fine:

ERLANG
4> Age = 30.
30
5> 30 = Age.
30

Why single assignment?

Because a value never changes after binding, you can read code without tracking "what is the variable now?". Two processes can never fight over a variable, and no lock is needed. Debugging is easier: if Total is wrong, there is exactly one place where it was bound.

In a function you create new variables for new values:

ERLANG
total_price(Price, Quantity, TaxRate) ->
    Subtotal = Price * Quantity,
    Tax = Subtotal * TaxRate,
    Subtotal + Tax.

Each step gets a fresh name. A common habit is to number them, State0, State1, State2, when you transform a value in stages:

ERLANG
update(State0) ->
    State1 = State0#{count => 1},
    State2 = State1#{ready => true},
    State2.

The match operator does more

Because = is pattern matching, the left side can be a structure and the variables inside get bound by destructuring:

ERLANG
1> {Name, Age} = {"Ada", 36}.
{"Ada",36}
2> Name.
"Ada"
3> [First, Second | Rest] = [10, 20, 30, 40].
[10,20,30,40]
4> First.
10
5> Rest.
[30,40]
6> {ok, Value} = {ok, 99}.
{ok,99}
7> {ok, Value2} = {error, nope}.
** exception error: no match of right hand side value {error,nope}

The last line is an intentional crash: it asserts that the result is {ok, _}. This "assert by matching" is a common Erlang idiom. You will see it more in Pattern Matching.

The anonymous variable

An underscore alone means "match anything, bind nothing":

ERLANG
1> {_, Second, _} = {a, b, c}.
{a,b,c}
2> Second.
b

Every _ is independent, so {_, _} = {1, 2} matches even though the values differ. A name starting with an underscore, such as _Reason, is a normal variable that the compiler will not warn about if unused. It still binds, so using it twice in the same pattern requires the values to be equal.

Variables bound in a pattern are the same variable

When a variable appears twice in one pattern, both occurrences must match equal values:

ERLANG
1> {X, X} = {5, 5}.
{5,5}
2> {Y, Y} = {5, 6}.
** exception error: no match of right hand side value {5,6}

This gives a compact way to check equality while destructuring.

Scope

A variable lives in the function clause where it is bound; the same name in another clause is unrelated.

ERLANG
f(0) ->
    Result = zero,
    Result;
f(N) ->
    Result = nonzero,
    {Result, N}.

Each clause has its own Result. Variables bound inside a case, if or receive branch are visible after it only if every branch binds them. The compiler warns about "unsafe" variables when only some branches bind a name, and using such a variable afterwards is a compile error.

ERLANG
bad(X) ->
    case X of
        1 -> Y = one;
        _ -> ok
    end,
    Y.        % error: variable 'Y' unsafe in 'case'

Funs (anonymous functions) can read variables from the surrounding code, which is called a closure. The variable is captured by value, since it can never change anyway.

Stand-ins in JavaScript

The first sample imitates single binding; the second imitates matching {X, X}. They are not Erlang.

JS Stand-in: an environment that binds once (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: destructuring with a repeated variable (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does X = 5, X = 6 do in the same scope?

    X is bound to 5 once. The second line is a match of 5 against 6, which fails.
  2. 2. Which of these is a valid variable name?

    Variables start with an uppercase letter or underscore. total is an atom.
  3. 3. What is the purpose of a lone underscore in a pattern?

    _ is the anonymous variable: it matches any value and is never bound.
  4. 4. What happens with {Y, Y} = {5, 6}?

    The same variable twice in one pattern requires equal values.

Summary

  • Variables start with a capital letter or underscore and are bound once.
  • = is the match operator: it binds unbound variables and checks bound ones.
  • Use new names for new values; numbered names like State1 are common.
  • _ matches anything without binding; _Name is a normal variable the compiler ignores if unused.
  • Variables are scoped to a function clause, and branch-only bindings are unsafe.

Next: Operators and Comparison