суббота, 2 апреля 2011 г.

Erlang Basics от Alan Castro


Erlang Basics

April 26, 2010 – Belo Horizonte, Brazil

Introduction

In this tutorial I’ll be talking about Erlang and showing some really basic programming examples. This tutorial is created for anyone who wants to start getting their hands dirty with this great language. I’ll make a small introduction to the Erlang language talking a little about the gains you have when using it, go through a simple installation on a Ubuntu 9.10machine, talk a little about the programming environment, and describe some of it’s basic types.

The Erlang Language

Erlang is a strictdynamically typed functional language with support for concurrency, communication, distribution, fault tolerance, code reloading, automatic memory management and support for multiples platforms. Erlang strenght resides on it’s lightweight concurrency model with massive process scalabality. This means that you can develop a high level, concurrent, robust, soft real-time system that will scale in line with demand. Since today’s most applications must answer to millions of requests per second, Erlang is a good way to go!

Installation

If you got to this section you may have some interest in learning Erlang, so let’s stop talking and get to business. This tutorial was created on Ubuntu 9.10, if you want to install on any other platform take a look at the Erlang Official Site and look for a binary useful for you, if you don’t find it you can always get the source. The installation is very simple. Just run the following command on your terminal:
$ sudo apt-get install erlang

Erlang Shell

Now that you have everything installed, let’s get used to the Erlang programming environment. Erlang binaries comes with an emulator where you can run any sequence of Erlang code. To give it a try run your erlang shell and start typing anything ending with a ‘.’(dot).
$ erl
Erlang R13B03 (erts-5.7.4) [source] [64-bit] [smp:4:4] [rq:4]
[async-threads:0] [kernel-poll:false]

Eshell V5.7.4  (abort with ^G)
1> 15782.
15782
2> erlang_rox.
erlang_rox
3> "erlang rox string.".
"erlang rox string."
4> 0.5.
0.5
5> halt().
Use halt() function or CTRL+c to close your emulator. The Shell has a lot more useful functions to be used, so for more details about it visit the Erlang Shell Documentation.

Variables

Variables are not variable in functional programming, this means that you can’t reassign a value to it. In Erlang a variable must have it’s first letter capitalize followed by any letter (upper or lower case), digits and ‘_’.
1> Variable = 1.
1
2> MyOther_Var = Variable.
1
3> Variable = 2.
** exception error: no match of right hand side value 2
4> f(Variable).
ok
5> Variable = 2.
2
Note that I used the f() function to reset a variable so it can be used again (it only works in the shell), this kind of information is found at the shell documentation site.

Basic Types

Before talking about the basic types it’s important that you know that when I say that something has a 1 word length, it means that in 32-bit systems it uses 4 bytes on memory and in 64-bit systems it uses 8 bytes.

Integer

In Erlang an integer is any representation of a positive or negative whole number, and they have an arbitrary size. For integers that are small enough, it uses one machine word in memory but if they get larger Erlang allocates extra memory space automatically. Erlang also let’s you express integers in other bases, using: Base#Number.
Type some in the shell:
1> 5.
5
2> 1987892029820989081712781657221.
1987892029820989081712781657221
3> 2#1010. 
10
4> 16#F.   
15

Floats

Floats are representations of real numbers. Erlang uses 64-bit IEEE 754-1985 float representation, double precision. There is a slightly difference when using float numbers in Erlang, it’s not possible to use .54 you must put a 0 in front of it, 0.54.
See some examples in the shell:
1> 5.9.
5.9
2> 10.5E-10.
1.05e-9
3> .54.
* 1: syntax error before: 54
Note that 10.5E-10 is the same as saying: 10.5 × 10 -10 .

Examples of some operations with numbers

1> 5 + 9.5.
14.5
2> 10 * 81
810.
3> 14 / 5
2.8
4> 14 div 5
2
5> 14 rem 5
4

Atoms

Atoms are constant literals that stand for themselves with their own name as value. Atoms starts with a lowercase letter or are delimited by single quotes, and you can use letters, digits, spaces, ‘@’, ‘.’, and ‘_’ for the rest. They occupy 1 word in memory.
Comparison is the only operation that atoms are allowed to be used with, which is very efficiently implemented by Erlang. In real applications atoms are used to express data that are coupled with it. 
One thing to keep in mind is that an atom is kept in an atom table , which is not garbage collected, that stays in memory, so beware of atoms usage. Erlang has an atom creation limit, that is 1048577 atoms at max per application.
1> my_new_atom.
my_new_atom
2> 'my new atom'.
'my new atom'
3> alan@zunnit.com
'alan@zunnit.com'

Booleans

There is no native boolean type in Erlang. They are represented by two atoms: true and false. Since booleans are simple atoms they occupy 1 word in memory too.
1> true and false.
false
2> true or false.
true
3> true xor false.
true
4> not true.
false
Note that the boolean operators and and or will always evalute both side of the operator. If you want the right side to be evaluated only when needed, use: andalso and oralso.

Binaries

A binary is a raw sequence of 8-bits bytes. Binaries are very efficient in moving around large amounts of data, so it’s generally used for socket programming, file operations, etc. Binaries are expressed in Erlang using a Bit-Syntax, enclosing data aroung << and >>, notice no space between them. There is a lot more into binaries that I won’t cover here, so you can take a look at Learn you some Erlang web site or Bit Syntax Expressions for more information about it.
Some binaries examples:
1> <<1, 2, 3, 4, 5>>. 
<<1,2,3,4,5>>
2> <<"strings", "can", "too">>.        
<<"stringscantoo">>
3> <<atoms_cant>>.
** exception error: bad argument

Tuples

Tuples are data types used to keep a collection of items, not necessarilly of the same type. They are written in form of {Element1, Element2, ..., ElementN}. Examples:
1> {true, false}.
{true, false}
2> {name, "Alan", age, 23}.
{name, "Alan", age, 23}
3> {name, "Alan", address, {city, "Belo Horizonte", country, "Brazil"}}.
{name, "Alan", address, {city, "Belo Horizonte", country, "Brazil"}}
A tuple size is of 2 words plus the size of each element in it. So for example if you have a tuple like {age, 23} then the size in words is: 2 (tuple) + 1(atom) + 1(integer) = 4 words.
In real applications tuples stores structured information.

Lists

Lists are one of the most important data type in any functional language, generally recursive functions iterate over them. In Erlang the most simple form of a list is []. Lists can hold any other data type and the elements are separated by comma.
Examples:
1> [true, false].
[true, false]
2> [1, 2, 3, 4, 5].
[1, 2, 3, 4, 5]
3> [1, [2], [3, [4]]].
[1, [2], [3, [4]]]
In Erlang characters are represented by integers and strings are lists of characters. It’s possible to see which integer is associated with a char, using a $ followed by the character you want to see.
Take a look:
1> $b.
98
2> [$e, $r, $l].
"erl"
3> [85, 86, 87].
"UVW"

Conclusion

I’ve made this tutorial so you can get used to the Erlang syntax, since it’s not a language that everyone got their hands on, and get to know it’s basic data types. Next articles that I’ll be posting here, will show some of my dayly experiences with Erlang and some other languages and tools that I work with. If you want to see more about data types and some basic Erlang visit this site: Learn you Some Erlang.

Комментариев нет:

Отправить комментарий