0% found this document useful (0 votes)
37 views23 pages

Tutorial 11

Erlang is a functional programming language with built-in support for concurrency, distribution, and fault tolerance. It is suitable for applications that require handling a large number of concurrent activities, scalability across multiple servers, and fault tolerance. The document describes how to install Erlang on Ubuntu, write a simple "Hello World" program in Erlang, and explains some basic concepts of the language including functions, modules, and built-in data types.

Uploaded by

arya hajari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views23 pages

Tutorial 11

Erlang is a functional programming language with built-in support for concurrency, distribution, and fault tolerance. It is suitable for applications that require handling a large number of concurrent activities, scalability across multiple servers, and fault tolerance. The document describes how to install Erlang on Ubuntu, write a simple "Hello World" program in Erlang, and explains some basic concepts of the language including functions, modules, and built-in data types.

Uploaded by

arya hajari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

COMP348

PRINCIPLES OF PROGRAMMING LANGUAGES

TUTORIAL 11
Erlang Intro

COMP 348 Principles of Programming Languages


Fall 2022
Erlang is a functional programming language which also has a runtime environment. It was
built in such a way that it had integrated support for concurrency, distribution and fault
tolerance.

Erlang should be used to develop your application, if you have the following requirements −

● The application needs to handle a large number of concurrent activities.


● It should be easily distributable over a network of computers.
● There should be a facility to make the application fault-tolerant to both software and
hardware errors.
● The application should be scalable. This means that it should have the ability to
span across multiple servers with little or no change.
● It should be easily upgradable and reconfigurable without having to stop and restart
the application itself.
● The application should be responsive to users within certain strict timeframes.

COMP 348 Principles of Programming Languages 2


Setting Up Erlang on Ubuntu

● Run ` sudo apt update ` and ` sudo apt upgrade ` to update the list of package repositories
and installed packages.

● Run ‘ sudo apt install erlang ’ to download and install the latest version of Erlang on our
Ubuntu 20.04 desktop or server system using the APT package manager.

● Run ‘ erl ‘ To test Erlang programs, or to maintain, the Erlang shell is ideal. This is automatically installed
with Erlang and can be installed from the terminal by the command.

COMP 348 Principles of Programming Languages 3


( optional )
If wanted to get the latest packages from the official website or the previous slide was not working
a. Run ` sudo apt update `
b. Install common tools : ‘ sudo apt install curl wget gnupg apt-transport-https -y ‘
a. Add Erlang GPG key, to install the packages from the official repository of Erlang, the system needs to
verify the package we are getting are in the same state as they were released by its developers. For that GPG
key is needed :
‘ curl -fsSL https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc | sudo
gpg --dearmor -o /usr/share/keyrings/erlang.gpg ‘

a. Although we don’t need to add the repository to get the packages for installing Erlang on Ubuntu 20.04,
however, the version will not be the latest. Therefore, to get the latest version of this programming language,
here we are adding Erlang’s official repository, manually :
echo "deb [signed-by=/usr/share/keyrings/erlang.gpg] https://packages.erlang-
solutions.com/ubuntu $(lsb_release -cs) contrib" | sudo tee
/etc/apt/sources.list.d/erlang.list
a. To rebuild the APT package index cache : ` sudo apt update `
b. After adding the repository, we can download and install the latest version of Erlang on our Ubuntu 20.04
desktop or server system using the APT package manager : ‘ sudo apt install erlang ‘
c. To test Erlang shell : ‘ erl ‘

COMP 348 Principles of Programming Languages 4


Hello World
create a file ‘hello.erl‘ with the following content :

a. Create a file: ‘ nano hello.erl ‘


b. Write the following code:

-module(hello). % The name of our module.

-export([helloworld/0]). % Declaration of the function that we want to


export from the module.

helloworld() -> io:format("Hello World ~n"). % What is to happen when

the function is called, here: Hello world is to be written on the screen.

a. Save the file using Ctrl+O, hit the Enter key, and Ctrl+X to exit the text editor

COMP 348 Principles of Programming Languages 5


Compile and run the created erlang program.

a. Switch to erlang shell: erl

b. compile the program using: c(hello).

c. Run the program: hello:helloworld().

COMP 348 Principles of Programming Languages 6


Compile and run the created erlang program without dropping into Erlang shell (Eshell ).

a. Compile the file: erlc hello.erl


b. Run the created .beam file: erl -noshell -s hello helloworld -s init stop

Run the helloworld function in hello module

Note : with using ‘-s init stop’ Erlang environment will shutdown once the program is finished, as
shown if it is not used after finishing the program still Erlang environment is running and need to
quit from it

COMP 348 Principles of Programming Languages 7


Pre-built Attributes
Export :
● The exports attribute will take a list of functions and arity to export for consumption by other
modules. It will define the module interface.

-export([FunctionName1/FunctionArity1,.,FunctionNameN/FunctionArityN])

Import :
● The import attribute is used to import functions from another module to use it as local.

-import (modulename , [functionname/parameter]).

-module(helloworld).
-author("XXX").
-version("1.0").
-import(io,[fwrite/1]).
-export([start/0]).

COMP 348 Principles of Programming Languages 8


Function

-module(helloworld). ➔ fwrite is a function in the io module provided by


-export([add/2,start/0]).
the Erlang framework, for printing to the console.
➔ Both functions are defined with the export function. If
add(X,Y) ->
Z = X+Y, we don’t do this, we will not be able to use the

io:fwrite("~w~n",[Z]). function.
➔ One function can be called inside another. Here the
start() -> add function is calling from the start function.
add(5,6). ➔ Output: 11

COMP 348 Principles of Programming Languages 9


❏ Anonymous Functions:
➔ The anonymous function is defined
-module(helloworld). with the fun() keyword.
-export([start/0]). ➔ The Function is assigned to a
variable called Fn.
start() ->
➔ The Function is called via the
Fn = fun() ->
variable name.
io:fwrite("Anonymous Function ~n") end,
Fn(),

Add = fun(N) -> ➔ Output : Anonymous Function


io:fwrite("~w~n",[N+1]) end, 4
Add(3).

COMP 348 Principles of Programming Languages 10


❏ Multi-arity Functions :

functions can be defined with zero or more parameters. Function overloading is also
possible, wherein you can define a function with the same name multiple times, as long as
they have different number of parameters.
-module(helloworld).
-export([add/2,add/3,start/0]).

add(X,Y) ->
Z = X+Y,
io:fwrite("~w~n",[Z]).

add(X,Y,Z) ->
A = X+Y+Z, Output: 11
io:fwrite("~w~n",[A]). 17

start() ->
add(5,6),
add(5,6,6).
COMP 348 Principles of Programming Languages 11
Built-in Data Types
❏ Number : In Erlang, there are 2 types of numeric literals which are integers and floats.
-module(helloworld).
-export([start/0]).

start() -> Output : 2


io:fwrite("~w~n",[1+1]), 2.3
io:fwrite("~w~n",[1.1+1.2]),
6
io:fwrite("~w~n",[3*2]),
io:fwrite("~w~n",[8-1]),
7
io:fwrite("~w~n",[10/2]), 5.0
io:fwrite("~w~n",[3 rem 2]), 1
io:fwrite("~p~n",[2==2]), true
io:fwrite("~p~n",[3 < 2]), false
io:fwrite("~p~n",[3 > 2]). true

COMP 348 Principles of Programming Languages 12


➔ Note: When using the fwrite method to output

-module(helloworld). values to the console, there are formatting


-export([start/0]). parameters available which can be used to
output numbers as float or exponential numbers.
start() -> ➔ ~f option is specified it means that the
io:fwrite("~f~n",[1.1+1.2]), argument is a float which is written as [-
io:fwrite("~e~n",[1.1+1.2]), ]ddd.ddd
➔ ~e option is specified it means that the
% boolean expressions argument is a scientific notation which is

io:fwrite("~p~n",[not true]), written as [-]d.ddde+-ddd

io:fwrite("~p~n",[true and false]), Output: 2.300000


io:fwrite("~p~n",[true or false]). 2.30000e+0
false
false
true
COMP 348 Principles of Programming Languages 13
❏ Atom : An atom is a literal, a constant with name, that should begin with a lowercase letter.
An atom is to 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 @.

-module(helloworld).
-export([start/0]).

start() -> Note: Boolean data types in Erlang are the two
io:fwrite(atom1), reserved atoms: true and false.
io:fwrite("~n"),
io:fwrite(atom_1), -module(helloworld).
io:fwrite("~n"), -export([start/0]).
io:fwrite('atom 1'),
start() ->
io:fwrite("~n"). io:fwrite(2 =< 3). Output: true
Output: atom1
atom_1
atom 1
COMP 348 Principles of Programming Languages 14
❏ String : A String literal is constructed in Erlang by enclosing the string text in
quotations. Strings in Erlang need to be constructed using the double quotation marks
such as “Hello World”.

-module(helloworld).
-module(helloworld). -import(string,[left/2]).
-export([start/0]). -export([start/0]).

start() -> start() ->


Str1 = "This is a string", Str1 = "hello World",
io:fwrite("~p~n",[Str1]). Str2 = left(Str1,2),
io:fwrite("~p~n",[Str2]).

Output: “This is a string” Returns the sub string from the


original string based on the left hand
side of the string and the number.
Output: “he”

COMP 348 Principles of Programming Languages 15


❏ Methods available for Strings :

● len(str) : returns the length of a particular string


● equal(str1,str2) : returns a Boolean value on whether one string is equal to another.
● concat(str1,str2) : concats 2 strings and returns the concatenated string.
● str(str1,chr1) : returns the index position of a character in a string. (Chr1 − This is
the character which needs to be searched in the string.)
● substr(str1,start,number) : returns the sub string from the original string based on
the starting position and number of characters from the starting position.
● left(str1,number) :returns the sub string from the left of the string based on the
number of characters.

COMP 348 Principles of Programming Languages 16


❏ List : A list is a compound data type with a variable number of terms.
Each term in the list is called an element.
The number of elements is said to be the length of the list.

-module(helloworld).
-import(lists,[append/2]).
-export([start/0]).
Output: [1,2,3,4,5]
start() ->
Lst1 = [1,2,3],
Lst2 = append(Lst1,[4,5]),
io:fwrite("~w~n",[Lst2]),

COMP 348 Principles of Programming Languages 17


❏ Methods available for Lists :

● delete(element,List1) : Deletes an element from the list and returns a new list.
● droplast(List1) :Drops the last element of a List. The list should be non-empty,
otherwise the function will crash with a function_clause.
● duplicate(N,Elem) :Returns a list which contains N copies of the term Elem.
(Elem − The element which needs to be duplicated in the list)
● last(lst1) :Returns the last element of the list.
● max(lst1) :Returns the element of the list which has the maximum value.
● min(lst1) :Returns the element of the list which has the minimum value.
● nth(N,List) :Returns the Nth element of List.
● reverse(lst) : Reverses a list of elements.
● sort(lst) : Sorts a list of elements.

COMP 348 Principles of Programming Languages 18


❏ Tuple : A tuple is a compound data type with a fixed number of terms.
Each Term in the tuple is called as an element.
The number of elements is said to be the size of the tuple.

-module(helloworld).
-export([start/0]). ● is_tuple(tuple):determines if the term
provided is indeed a tuple or not and
start() ->
P = {john,24,{june,25}} , return true or false.
io:fwrite("~w",[tuple_size(P)]). ● list_to_tuple(list):converts a list to a tuple.
● tuple_to_list(tuple):converts a tuple to a
list.
Output: 3

COMP 348 Principles of Programming Languages 19


❏ Map :

get(key,map) :get the value of a


particular key in the map.
-module(helloworld).
-export([start/0]). Is_key(key,map) : determines if a
particular key is defined as a key in the
start() -> map.
Lst1 = [{"a",1},{"b",2},{"c",3}],
keys(map) :return all the keys from a
Map1 = maps:from_list(Lst1),
map.
io:fwrite("~p~n",[maps:find("a",Map1)]). put(key1,value1,map1) :add a key value
pair to the map.
Output: {ok,1} values(map) :return all the values from
a map.

COMP 348 Principles of Programming Languages 20


❏ Record :

-module(helloworld).
-export([start/0]).
-record(person, {name = "", id}).

start() ->
P = #person{name = "John",id = 1},
P1 = P#person{name = "Dan"}, Output: 1
io:fwrite("~p~n",[P1#person.id]), “Dan”
io:fwrite("~p~n",[P1#person.name]).

COMP 348 Principles of Programming Languages 21


❏ Example: record and anonymous function, foreach()

➔ The anonymous function is defined with the fun()


keyword. The Function is assigned to a variable
print_list(Stream, [H|T]) -> called Fn.
io:format(Stream, "~p~n", [H]), ➔ Note: [H|T] is a list and Erlang considers lists to
print_list(Stream, T); consist of a Head and a Tail. The head is the first
print_list(Stream, []) -> element, the tail is everything else
true. ➔ ~p : Writes the data with standard syntax in the
same way as ~w, but breaks terms whose
printed representation is longer than one line into
many lines and indents each line sensibly.
● Using foreach, print_list becomes:

foreach(fun(H) -> io:format(S, "~p~n",[H]) end, L)

COMP 348 Principles of Programming Languages 22


References

https://www.erlang-solutions.com/downloads/
https://www.tutorialspoint.com/erlang/erlang_data_types.htm

COMP 348 Principles of Programming Languages 23

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy