Thursday, October 11, 2007

Day 4: ERLANG - Expressions

1 Expression Evaluation

An expression in ERLANG could be composed of terms, variables or sub expressions.

An example ERLANG expression could be
Y = X + Z


2 Terms
The simplest form of expression is a term, that is an integer, float, atom, string, list or tuple. The return value is the term itself.

3 Variables
Variables start with an uppercase letter or underscore (_) and may contain alphanumeric characters, underscore and @.

Examples:
X
Name1
PhoneNumber
Phone_number
_
_Height

A variable itself is an expression. A variable bound to a value, returns the value. Unbound variables are allowed only in patterns.

Variables are bound to values using pattern matching. Erlang uses single assignment, a variable can only be bound once.

The anonymous variable is denoted by underscore (_) and can be used when a variable is required but its value can be ignored.

Example: [H_] = [1,2,3]

Variables starting with underscore (_), for example _Height, are normal variables, not anonymous. They are however ignored by the compiler in the sense that they will not generate any warnings for unused variables.

Example:

The following code

member(_, []) ->
[].
can be rewritten to be more readable:

member(Elem, []) ->
[].

This will however cause a warning for an unused variable Elem, if the code is compiled with the flag warn_unused_vars set. Instead, the code can be rewritten to:

member(_Elem, []) ->
[].

Note that since variables starting with an underscore are not anonymous, this will match:
{_,_} = {1,2}

But this will fail:
{_N,_N} = {1,2}

3. Patterns

No comments: