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

Day3: ERLANG - Data Types

ERLANG is very different from C. You have to "think in ERLANG way"

The data types seem strange to a "C" programmer. Let us attack one by one

1. Terms
A piece of data of any data type is called a term.


2. Number
There are two types of numeric literals,
  • integers
  • floats.

Besides the conventional notation, there are two Erlang-specific notations:
  • $char - ASCII value of the character char.
  • base#value - Integer with the base base, which must be an integer in the range 2..36.
Examples:
42

$A (evaluates to 65)

$\n (10)

2#101 (5)

16#1f (31)

2.3

2.3e3 (2300.00)

2.3e-3 (2.30000e-3)



3 Atom
An atom is a literal, a constant with name. An atom should be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @.

Examples:

hello
phone_number
'Monday'
'phone number'


4 Binary
A binary is used to store an area of untyped memory.
Binaries are expressed using the
bit syntax.


Examples:

<<10,20>>

<<"ABC">>



5 Reference

A reference is a term which is unique in an Erlang runtime system, created by calling make_ref/0.




6 Fun
A fun is a functional object. Funs make it possible to create an anonymous function and pass the function itself -- not its name -- as argument to other functions.

Example:

Fun1 = fun (X) -> X+1 end.

7 Port Identifier

A port identifier identifies an Erlang port. open_port/2, which is used to create ports, will return a value of this type.


8 Pid
A process identifier, pid, identifies a process. spawn/1,2,3,4, spawn_link/1,2,3,4 and spawn_opt/4, which are used to create processes, return values of this type.


Example:
spawn(m, f, []) returns <0.51.0>



9 Tuple

Compound data type with a fixed number of terms: {Term1,...,TermN}

Each term Term in the tuple is called an element. The number of elements is said to be the size of the tuple.


Examples:
P = {adam,24,{july,29}}



10 List

Compound data ty
pe with a variable number of terms. [Term1,...,TermN]

Each term Term in the list is called an element. The number of elements is said to be the length of the list.


Formally, a list is either the empty list [] or consists of a head (first element) and a tail (remainder of the list) which is also a list.

The latter can be expressed as [HT].

The notation [Term1,...,TermN] above is actually shorthand for the list [Term1[...[TermN[]]]].

Example:
[] is a list,
thus[c[]] is a list,
thus[b[c[]]] is a list,
thus[a[b[c[]]]] is a list, or
in short [a,b,c].



11 String
Strings are enclosed in double quotes ("), but is not a data type in Erlang.

Instead a string "hello" is shorthand for the list [$h,$e,$l,$l,$o], that is [104,101,108,108,111].

Two adjacent string literals are concatenated into one. This is done at compile-time and does not incur any runtime overhead.

Example:

"string" "42" is equivalent to "string42"


12 Record
A record is a data structure for storing a fixed number of elements. It has named fields and is similar to a struct in C. However, record is not a true data type. Instead record expressions are translated to tuple expressions during compilation. Therefore, record expressions are not understood by the shell unless special actions are taken.

Examples:

-module(person).
-export([new/2]).
-record(person, {name, age}).


new(Name, Age) ->
#person{name=Name, age=Age}.


13 Boolean
There is no Boolean data type in Erlang. Instead the atoms true and false are used to denote Boolean values.
Examples:

2=<3 evaluates to true

true or false evaluates to true


14 Escape Sequences


Within strings and quoted atoms, the following escape sequences are recognized:

\b - backspace
\d - delete
\e - escape
\f - form feed
\n - newline
\r - carriage return
\s - space
\t - tab
\v - vertical tab
\XYZ, \YZ, \Z - character with octal representation XYZ, YZ or Z
\^a...\^z\^A...\^Z - control A to control Z
\' - single quote
\" - double quote
\\ - backslash

15 Type Conversions
There are a number of build-in-functions (BIFs) for type conversions.

Examples:

atom_to_list(hello) evaluates to "hello"

list_to_atom("hello") evaluates to hello

binary_to_list(<<"hello">>) evaluates to "hello"

binary_to_list(<<104,101,108,108,111>>) evaluates to "hello"

list_to_binary("hello") evaluates to <<104,101,108,108,111>>

float_to_list(7.0) evaluates to "7.00000000000000000000e+00"

list_to_float("7.000e+00") evaluates to 7.00000

integer_to_list(77) evaluates to "77"

list_to_integer("77") evaluates to 77

tuple_to_list({a,b,c}) evaluates to [a,b,c]

list_to_tuple([a,b,c]) evaluates to {a,b,c}

term_to_binary({a,b,c}) evaluates to <<131,104,3,100,0,1,97,100,0,1,98,100,0,1,99>>

binary_to_term(<<131,104,3,100,0,1,97,100,0,1,98,100,0,1,99>>) evaluates to {a,b,c}




Day2: ERLANG - The language

1. The Hello World in ERLANG

From the era of "C", all text books start with the infamous "HelloWorld" program. I said "infamous", i really mean it, because it stresses on "printf" and almost all the kids from colleges/universities believe C is all about printf and scanf. I know it is debatable. But this blog stresses on ERLANG.

So the HelloWorld equivalent in ERLANG is below.

-module(fact).
-export([fac/1]).


fac(0) ->
1;

fac(N) when N > 0 ->
N * fac(N-1).


If the power of "C" is in "printf" (just kidding), the power of ERLANG is in recursion. The above snippet can be read as two clauses

Clause 1: Factorial of Zero is 1

Clause 2: Factorial of a number N is N times factorial of (N-1) when N is greater than ZERO.

Yes, the language simply accepts the clauses as it is.

The fist two lines tells the ERLANG runtime, that it is a ERLANG module named "fact" and the module exports a function called "fac" which takes one parameter.

2. How it differs from other popular programming languages like C, PASCAL etc

ERLANG is very different from the procedural programming langugages. Let us see the major differences

2.1 Variables can be assigned only once
It may seem to be a misnomer - the variables can be assigned a value only once!

2.2 No iteration, only recursion
ERLANG doesnt support iteration, you have to implement your logic in a recursive manner. I am not sure, why the langugage designers chose this strategy, it may have some relations with the previous limitation - a variable can be assigned only once, and hence we cannot have a loop counter

But there are other languages which dont support iteration, like, PROLOG, LISP etc

2.3 There are no pointers
Pointers are not there - but you dont need a pointer in a ERLANG world.

2.4 Functions look like clauses in predicate logic
Clauses evaluates to values, and there is nothing like a RETURN from a function.
PROLOG is exactly like this. There are no functions in PROLOG, only clauses.

Day1: What is ERLANG

http://en.wikipedia.org/wiki/Erlang_(programming_language) sys

"Erlang is a general-purpose concurrent programming language and runtime system.

The sequential subset of Erlang is a functional language, with strict evaluation, single assignment, and dynamic typing.

For concurrency it follows the Actor model.

It was designed by Ericsson to support distributed, fault-tolerant, soft-real-time, non-stop applications.

It supports hot swapping so code can be changed without stopping a system."

Erlang was originally a proprietary language within Ericsson, but was released as open source in 1998. The Ericsson implementation primarily runs interpreted virtual machine code, but it also includes a native code compiler (not supported on all platforms), developed by the High-Performance Erlang Project (HiPE) at Uppsala University. It also now supports interpretation via escript as of r11b-4