A ‘little’ discovery about ‘=’ and ‘anonymous variables’


One thing I had clear about erlang (see my first post) is that in erlang a variable gets a value and never change it, it looks a bit different in reality.

When you execute something like X = 5. Erlang read ‘=’ as a matching operator, “X must be equal to 5”, so to become true the phrase it sets X the value of 5.

So … if you have a tuple like:

Person = {person, simone, 26}.

you can make something like:

{person, Name, Age} = Person.

In that way you will have Name with ‘simone’ as value and Age with ’26’. Good!

Another try:

Person = {person,
{name, simone},
{age, 26},
{location, italy}}.

To get the name you have to:

{_,{_,Who},_,_} = Person.

‘_’ is called anonymous variable and it represents variables not interesting for us. Notice that the structure of the first operand is the same of the Person, it simply has many ‘_’ where there is non interesting data.

Another example:

Desk = {desk,
{material, plastic},
{height, 50}}.

I can get material and height values simply doing:

{_, {_, Material}, {_, Height}} = Desk.

Now I’ll have two variables (Material and Height) with values ‘plastic’ and ’50’. Good 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: