Erlang Datatypes

Erlang Variables

I will introduce the most datatypes that being used in Erlang such as number, atom, function, tuple, map, list, record, and boolean.

Number
There are two datatypes of numeric are integers and floats.

Example:

1
2
3
4
1> 42.
42
2> 2.3.
2.3

Atom
Atom is a literal, a constant with name. 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 @ sign.

Example:

1
2
3
4
hi
phone_number
'Sunday'
'phone number'

Fun
Fun is a functional object. Funs make it possible to create an anonymous function and pass the function itself.

Example:

1
2
3
4
1> Fun1 = fun (X) -> X+1 end.
#Fun<erl_eval.6.39074546>
2> Fun1(6).
7

Tuple
Tuple is a compound data type, it consists of elements of any datatypes.

Syntax:

1
{Element1, Element2, ..., ElementN}

Example:

1
2
3
4
5
6
7
8
9
10
> T = {bunlong, 27, {may, 17}}.
{bunlong, 27, {may, 17}}
> element(1, T).
bunlong
> T2 = setelement(2, T, 25).
{bunlong, 25, {may, 17}}
> tuple_size(T).
3
> tuple_size({}).
0

Map
Map is a compound data type with a variable number of key-value associations.

Syntax:

1
#{Key1=>Value1,...,KeyN=>ValueN}

Example:

1
2
3
4
5
6
7
8
9
10
11
12
1> M1 = #{name=>bunlong,age=>26,date=>{may,07}}.
#{age => 26,date => {may,07},name => bunlong}
2> maps:get(name,M1).
bunlong
3> maps:get(date,M1).
{may,07}
4> M2 = maps:update(age,27,M1).
#{age => 27,date => {may,07},name => bunlong}
5> map_size(M).
3
6> map_size(#{}).
0

List
As in all functional programming language, list is one of the most used datatyped. Again, Erlang borrows the list syntax from Prolog. Because of their importance. List is a compound data type with a variable number of terms.

Syntax:

1
[Element1, Element2, ..., ElementN]

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
> L = [a, 2, {c, 4}].
[a, 2, {c, 4}]
> [H|T] = L.
[a, 2, {c, 4}]
> H.
a
> T.
[2, {c, 4}]
> L2 = [d|T].
[d, 2, {c, 4}]
> length(L).
3
> length([]).
0

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.

Example:

1
2
3
4
5
6
7
8
-module(person).
-export([new/2]).
-record(person, {name, age}).
new(Name, Age) ->
  #person{name=Name, age=Age}.

% > person:new(bunlong, 27).
% {person, bunlong, 27}

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

Example:

1
2
3
4
> 2 =< 3.
true
> true or false.
true

So are so good, there are some other datatypes, such as binary, reference, Pid, etc. I will explain them when needed. see you in the next articles! :)