May
07
Posted on 07-05-2007
Filed Under (Erlang, Programming) by Federico Feroldi on 07-05-2007

The first thing you should learn about a new language is its small bricks, the data types. Once you know how to structure your data you can build your application on it.
So, let’s take a brief look at Erlang’s data types.

Numbers

Erlang supports integer and floating point numbers. Integer numbers can have almost unlimited size. Try this on the Erlang shell (erl):

2> 4534535*543636345*3445343*6564574523432.
55754546761558695184405188371500200

You can also have floating point numbers, but they have limited precision and size:

3> 3 / 2.  
1.50000
4> 2 * 1.5.
3.00000

Strings

Strings are made of quoted text like “This is a String!”. Erlang deals with strings as they were lists of characters. Unfortunately when Erlang was born, his father didn’t knew about Unicode, so we can just have Latin-1 characters (ASCII 0-255) so far.

Atoms

Atoms are names, constant text strings that you can use like C’s enums or Ruby’s symbols.
Atoms must be unquoted alphanumeric strings that begins with a lower case letter. You can also have non alphanumeric atoms that begins with any letter by quoting the string with a single quote.
Examples: apple, mice, dog, banana, ‘Valentina’, ‘This is an Atom!’.

Tuples

Tuples are fixed sets of data. You cannot add anything to a tuple once you created it. Tuples can contain other tuples, atom, strings and lists.
Examples: {this, is, “a tuple”, with, 6, ‘Elements!’}, {1 + 2, milk, banana, [ 1, 2, 3 ]}.

Lists

Lists are similar to tuples but they can contain an undefined amount of items of any type:

10> [1, 2, 3, {this, is, a, tuple}, anatom, [a, list]].
[1,2,3,{this,is,a,tuple},anatom,[a,list]]

It’s also very easy to split a list into his head and his tail, and that’s also the only way to access his elements (you cannot extract the nth element before the nth-1 elements):

11> [Head | Tail] = [a, b, c, d].
[a,b,c,d]
12> Head.
a
13> Tail.
[b,c,d]

You can also create new lists by adding elements in front or at the end of an existing one:

14> [1, 2, 3 | Tail].
[1,2,3,b,c,d]
15> [Head|[1,2,3]].
[a,1,2,3]

Funs

Last but not least we have funs that are anonymous functions. Erlang deals with funs as they were like any other data type. You can assign funs to variables, pass funs to as parameter to function calls and return funs as function results:

15> MyFun = fun(X) -> X * 2 end.
#Fun<erl_eval.6.72228031>
16> MyFun(5).
10
17> lists:map(MyFun, [1, 2, 3]).
[2,4,6]

That’s all for now! I hope to have made less mistakes than the last time! :)

Share and Enjoy:
  • Digg
  • del.icio.us
  • DZone
  • Reddit
  • Technorati
  • YahooMyWeb
(46) Comments    Read More   
Post a Comment
Name:
Email:
Website:
Comments: