Variables and single assignment
| Bind once | |
| No rebinding | |
| The underscore | |
| Where variables live |
Bind once
Variables start with an uppercase letter or an underscore. The equals sign binds a name to a value, and the name then stands for that value everywhere in its scope.
1> Name = "Ada".
"Ada"
2> Answer = 42.
42
1> Name = "Ada".
"Ada"
2> Answer = 42.
42
No rebinding
Single assignment means a bound name never changes. The equals sign is a match: it checks that the right side equals the stored value, and fails loudly when it does not.
This looks strict at first and pays off in concurrent code, where two processes can never race over a mutable cell.
1> Answer = 42.
42
2> Answer = 42. % ok: the same value
42
3> Answer = 43.
** exception error: no match of right hand side value 43
1> Answer = 42.
2> Answer = 42. % ok: the same value
3> Answer = 43.
** exception error: no match of right hand side value 43
The underscore
The lone underscore matches anything and binds nothing. It says: I do not care about this part.
An underscore with a name, like _Name, binds the value but warns that you mean to ignore it.
1> {ok, _} = {ok, 7}.
{ok,7}
2> {error, _Reason} = {error, enoent}.
{error,enoent}
1> {ok, _} = {ok, 7}.
{ok,7}
2> {error, _Reason} = {error, enoent}.
{error,enoent}
Where variables live
A binding lives in the function clause that made it. Another clause of the same function starts with a clean slate, even when it runs the same name.
The shell is one big clause, which is why a name typed once stays bound until you restart erl.
Next: Numbers
Article author: Arthur Isaev