Stratus3D

Software Engineering, Web Development and 3D Design

Everything You Need to Know About Erlang's Magic _ Variable

I had someone ask me what happened to values assigned to the underscore variable in Erlang. I realized I didn’t have a clear understand of the way variables beginning with an underscore handled. I decided to re-read the Erlang documentation on variables.

To summarizing what the documentation says, all variables could be put into three groups:

  • Normal variables
  • Normal variables prefixed with with an underscore
  • The anonymous variable (a single underscore)

###Erlang Variables All types of variables must start with either an uppercase letter or an underscore. They may contain alphanumeric characters, the underscore and the @ symbol. All variables are bound via Pattern Matching. At runtime no variables are special except for the anonymous variable.

##Normal variables Normal variables start with an uppercase letter. Pattern matching and all the compile time warnings work normally. Example:

1> {First, Second} = {foo, bar}.
{foo, bar}
2> First.
foo
3> Second.
bar

##Normal variables prefixed with an underscore When a variable is prefixed with an underscore pattern matching and everything at runtime works like a normally. Values are still bound as they normally would and patterns such as this fail like they normally would. {_Val,_Val} = {foo,bar} fails because the first and second items in the tuple are different. The only difference is at compile time. Normally the compiler generates a warning when a value is bound to a variable and the variable is not later used. Often an important value is returned from a function call but the value is unused. By prefixing the variable with an underscore, the variable retains it’s useful name and does not generate any compile time warnings. Example:

1> {_First, _Second} = {foo, bar}.
{foo, bar}
2> _First.
foo
3> _Second.
bar

##The anonymous variable The anonymous variable is denoted by a single underscore (_). The anonymous variable is used when a variable is required but the value needs to be ignored. When a value is assigned to the anonymous variable the value is never bound to the variable. Since the value is never bound it can be used multiple times in a pattern and each time it is allowed to match a different value. Example:

1> {_, _} = {foo, bar}.
{foo, bar}
2> _.
* 1: variable '_' is unbound 
4> {_, Second} = {foo, bar}.
{foo, bar}
5> _.
* 1: variable '_' is unbound 
6> Second.
bar

For more information check out the Erlang documentation on variables