Elixir binding - does Elixir test for equality

In

a =1

Does Elixir test for equality before binding 1 to a?

No, by default a is allowed to be re-bound if it is already bound, shadowing previous bindings lexically.

However you can prevent a variable from being rebound via ^.

iex(1)> a = 1
1
iex(2)> a = 2
2
iex(3)> ^a = 3
** (MatchError) no match of right hand side value: 3
    (stdlib) erl_eval.erl:453: :erl_eval.expr/5
    (iex) lib/iex/evaluator.ex:257: IEx.Evaluator.handle_eval/5
    (iex) lib/iex/evaluator.ex:237: IEx.Evaluator.do_eval/3
    (iex) lib/iex/evaluator.ex:215: IEx.Evaluator.eval/3
    (iex) lib/iex/evaluator.ex:103: IEx.Evaluator.loop/1
    (iex) lib/iex/evaluator.ex:27: IEx.Evaluator.init/4
iex(3)> ^a = 2
2
6 Likes

Why is bind the correct word and not assign?

1 Like

It’s because of the pattern matching.
You can learn more about this here.

1 Like

The documentation uses assign instead of bind.

The documentation uses both interchangably. Perhaps we should pick one :slight_smile:

2 Likes