Erlang – Macros

Erlang – Macros ”; Previous Next Macros are generally used for inline code replacements. In Erlang, macros are defined via the following statements. -define(Constant, Replacement). -define(Func(Var1, Var2,.., Var), Replacement). Following is an example of macros using the first syntax − Example Live Demo -module(helloworld). -export([start/0]). -define(a,1). start() -> io:fwrite(“~w”,[?a]). From the above program you can see that the macro gets expanded by using the ‘?’ symbol. The constant gets replaced in place by the value defined in the macro. The output of the above program will be − Output 1 An example of a macro using the function class is as follows − Example Live Demo -module(helloworld). -export([start/0]). -define(macro1(X,Y),{X+Y}). start() -> io:fwrite(“~w”,[?macro1(1,2)]). The output of the above program will be − Output {3} The following additional statements are available for macros − undef(Macro) − Undefines the macro; after this you cannot call the macro. ifdef(Macro) − Evaluates the following lines only if the Macro has been defined. ifndef(Macro) − Evaluates the following lines only if Macro is undefined. else − Allowed after an ifdef or ifndef statement. If the condition was false, the statements following else are evaluated. endif − Marks the end of an ifdef or ifndef statement. When using the above statements, it should be used in the proper way as shown in the following program. -ifdef(<FlagName>). -define(…). -else. -define(…). -endif. Print Page Previous Next Advertisements ”;

Erlang – Recursion

Erlang – Recursion ”; Previous Next Recursion is an important part of Erlang. First let’s see how we can implement simple recursion by implementing the factorial program. Example Live Demo -module(helloworld). -export([fac/1,start/0]). fac(N) when N == 0 -> 1; fac(N) when N > 0 -> N*fac(N-1). start() -> X = fac(4), io:fwrite(“~w”,[X]). The following things need to be noted about the above program − We are first defining a function called fac(N). We are able to define the recursive function by calling fac(N) recursively. The output of the above program is − Output 24 Practical Approach to Recursion In this section, we will understand in detail the different types of recursions and its usage in Erlang. Length Recursion A more practical approach to recursion can be seen with a simple example which is used to determine the length of a list. A list can have multiple values such as [1,2,3,4]. Let’s use recursion to see how we can get the length of a list. Example Live Demo -module(helloworld). -export([len/1,start/0]). len([]) -> 0; len([_|T]) -> 1 + len(T). start() -> X = [1,2,3,4], Y = len(X), io:fwrite(“~w”,[Y]). The following things need to be noted about the above program − The first function len([]) is used for the special case condition if the list is empty. The [H|T] pattern to match against lists of one or more elements, as a list of length one will be defined as [X|[]] and a list of length two will be defined as [X|[Y|[]]]. Note that the second element is a list itself. This means we only need to count the first one and the function can call itself on the second element. Given each value in a list counts as a length of 1. The output of the above program will be − Output 4 Tail Recursion To understand how the tail recursion works, let’s understand how the following code in the previous section works. Syntax len([]) -> 0; len([_|T]) -> 1 + len(T). The answer to 1 + len(Rest) needs the answer of len(Rest) to be found. The function len(Rest) itself then needed the result of another function call to be found. The additions would get stacked until the last one is found, and only then would the final result be calculated. Tail recursion aims to eliminate this stacking of operation by reducing them as they happen. In order to achieve this, we will need to hold an extra temporary variable as a parameter in our function. The aforementioned temporary variable is sometimes called accumulator and acts as a place to store the results of our computations as they happen in order to limit the growth of our calls. Let’s look at an example of tail recursion − Example Live Demo -module(helloworld). -export([tail_len/1,tail_len/2,start/0]). tail_len(L) -> tail_len(L,0). tail_len([], Acc) -> Acc; tail_len([_|T], Acc) -> tail_len(T,Acc+1). start() -> X = [1,2,3,4], Y = tail_len(X), io:fwrite(“~w”,[Y]). The output of the above program is − Output 4 Duplicate Let’s look at an example of recursion. This time around let’s write a function which takes an integer as its first parameter and then any other term as its second parameter. It will then create a list of as many copies of the term as specified by the integer. Let’s look at how an example of this would look like − Live Demo -module(helloworld). -export([duplicate/2,start/0]). duplicate(0,_) -> []; duplicate(N,Term) when N > 0 -> io:fwrite(“~w,~n”,[Term]), [Term|duplicate(N-1,Term)]. start() -> duplicate(5,1). The output of the above program will be − Output 1, 1, 1, 1, 1, List Reversal There are no bounds to which you can use recursion in Erlang. Let’s quickly now look at how we can reverse the elements of a list using recursion. The following program can be used to accomplish this. Example Live Demo -module(helloworld). -export([tail_reverse/2,start/0]). tail_reverse(L) -> tail_reverse(L,[]). tail_reverse([],Acc) -> Acc; tail_reverse([H|T],Acc) -> tail_reverse(T, [H|Acc]). start() -> X = [1,2,3,4], Y = tail_reverse(X), io:fwrite(“~w”,[Y]). The output of the above program will be − Output [4,3,2,1] The following things need to be noted about the above program − We are again using the concept of temporary variables to store each element of the List in a variable called Acc. We then call tail_reverse recursively, but this time around, we ensure that the last element is put in the new list first. We then recursively call tail_reverse for each element in the list. Print Page Previous Next Advertisements ”;

Erlang – Exceptions

Erlang – Exceptions ”; Previous Next Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained. Exception normally disrupts the normal flow of the application, which is the reason why we need to use Exception handling in our application. Normally when an exception or error occurs in Erlang, the following message will be displayed. {“init terminating in do_boot”, {undef,[{helloworld,start,[],[]}, {init,start_it,1,[]},{init,start_em,1,[]}]}} Crash dump will be written to − erl_crash.dump init terminating in do_boot () In Erlang, there are 3 types of exceptions − Error − Calling erlang:error(Reason) will end the execution in the current process and include a stack trace of the last functions called with their arguments when you catch it. These are the kind of exceptions that provoke the runtime errors above. Exists − There are two kinds of exits: ”internal” exits and ”external” exits. The internal exits are triggered by calling the function exit/1 and make the current process stop its execution. The external exits are called with exit/2 and have to do with multiple processes in the concurrent aspect of Erlang. Throw − A throw is a class of exception used for cases that the programmer can be expected to handle. In comparison with exits and errors, they don”t really carry any ”crash that process!” intent behind them, but rather they control the flow. As you use throws while expecting the programmer to handle them, it”s usually a good idea to document their use within a module using them. A try … catch is a way to evaluate an expression while letting you handle the successful case as well as the errors encountered. The general syntax of a try catch expression is as follows. Syntax try Expression of SuccessfulPattern1 [Guards] -> Expression1; SuccessfulPattern2 [Guards] -> Expression2 catch TypeOfError:ExceptionPattern1 -> Expression3; TypeOfError:ExceptionPattern2 -> Expression4 end The Expression in between try and of is said to be protected. This means that any kind of exception happening within that call will be caught. The patterns and expressions in between the try … of and catch behave in exactly the same manner as a case … of. Finally, the catch part – here, you can replace TypeOfError by either error, throw or exit, for each respective type we”ve seen in this chapter. If no type is provided, a throw is assumed. Following are some of the errors and the error reasons in Erlang − Error Type of Error badarg Bad argument. The argument is of wrong data type, or is otherwise badly formed. badarith Bad argument in an arithmetic expression. {badmatch,V} Evaluation of a match expression failed. The value V did not match. function_clause No matching function clause is found when evaluating a function call. {case_clause,V} No matching branch is found when evaluating a case expression. The value V did not match. if_clause No true branch is found when evaluating an if expression. {try_clause,V} No matching branch is found when evaluating the of-section of a try expression. The value V did not match. undef The function cannot be found when evaluating a function call.. {badfun,F} Something is wrong with a fun F {badarity,F} A fun is applied to the wrong number of arguments. F describes the fun and the arguments. timeout_value The timeout value in a receive..after expression is evaluated to something else than an integer or infinity. noproc Trying to link to a non-existing process. Following is an example of how these exceptions can be used and how things are done. The first function generates all possible types of an exception. Then we write a wrapper function to call generate_exception in a try…catch expression. Example -module(helloworld). -compile(export_all). generate_exception(1) -> a; generate_exception(2) -> throw(a); generate_exception(3) -> exit(a); generate_exception(4) -> {”EXIT”, a}; generate_exception(5) -> erlang:error(a). demo1() -> [catcher(I) || I <- [1,2,3,4,5]]. catcher(N) -> try generate_exception(N) of Val -> {N, normal, Val} catch throw:X -> {N, caught, thrown, X}; exit:X -> {N, caught, exited, X}; error:X -> {N, caught, error, X} end. demo2() -> [{I, (catch generate_exception(I))} || I <- [1,2,3,4,5]]. demo3() -> try generate_exception(5) catch error:X -> {X, erlang:get_stacktrace()} end. lookup(N) -> case(N) of 1 -> {”EXIT”, a}; 2 -> exit(a) end. If we run the program as helloworld:demo(). , we will get the following output − Output [{1,normal,a}, {2,caught,thrown,a}, {3,caught,exited,a}, {4,normal,{”EXIT”,a}}, {5,caught,error,a}] Print Page Previous Next Advertisements ”;

Erlang – Overview

Erlang – Overview ”; Previous Next 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 was originally developed to be used in several large telecommunication systems from Ericsson. The first version of Erlang was developed by Joe Armstrong, Robert Virding and Mike Williams in 1986. It was originally a proprietary language within Ericsson. It was later released as an open source language in year 1998. Erlang, along with OTP, a collection of middleware and libraries in Erlang, are now supported and maintained by the OTP product unit at Ericsson and widely referred to as Erlang/OTP. Why Erlang? 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. The official website for Erlang is https://www.erlang.org/. Print Page Previous Next Advertisements ”;

Erlang – File I/O

Erlang – File I/O ”; Previous Next Erlang provides a number of methods when working with I/O. It has easier classes to provide the following functionalities for files − Reading files Writing to files Seeing whether a file is a file or directory File Operation Methods in Erlang Let’s explore some of the file operations Erlang has to offer. For the purposes of these examples, we are going to assume that there is a file called NewFile.txt which contains the following lines of text Example1 Example2 Example3 This file will be used for the read and write operations in the following examples. Reading the Contents of a File One Line at a Time The general operations on files are carried out by using the methods available in the file library. For the reading of files, we would need to first use the open operation and then use the read operation which is available as a part of the file library. Following is the syntax for both of these methods. Syntax Opening a file – Open(File,Mode) Reading a file – read(FileHandler,NumberofBytes) Parameters File − This is the location of the file which needs to be opened. Mode − This is the mode in which the file needs to be opened in. Following are some of the available modes − Read − The file, which must exist, is opened for reading. Write − The file is opened for writing. It is created if it does not exist. If the file exists, and if write is not combined with read, the file will be truncated. Append − The file will be opened for writing, and it will be created if it does not exist. Every write operation to a file opened with append will take place at the end of the file. Exclusive − The file, when opened for writing, is created if it does not exist. If the file exists, open will return {error, exist}. FileHandler − This is the handle to a file. This handle is the one that would be returned when the file:open operation is used. NumberofByte − This is the number of bytes of information that needs to be read from the file. Return Value Open(File,Mode) − Returns a handle to the file, if the operation is successful. read(FileHandler,NumberofBytes) − Returns the requested read information from the file. For example -module(helloworld). -export([start/0]). start() -> {ok, File} = file:open(“Newfile.txt”,[read]), Txt = file:read(File,1024 * 1024), io:fwrite(“~p~n”,[Txt]). Output − When we run the above program, we will get the following result. Example1 Let us now discuss some other methods available for file operations − Sr.No. Method & Description 1 file_read Available to allow the reading of all the contents of a file at one time. 2 write Used to write the contents to a file. 3 copy used to make a copy of an existing file. 4 delete This method is used to delete an existing file. 5 list_dir This method is used to list down the contents of a particular directory. 6 make_dir This method is used to create a new directory. 7 rename This method is used to rename an existing file. 8 file_size This method is used to determine the size of the file. 9 is_file This method is used to determine if a file is indeed a file. 10 is_dir This method is used to determine if a directory is indeed a directory. Print Page Previous Next Advertisements ”;

Erlang – Binaries

Erlang – Binaries ”; Previous Next Use a data structure called a binary to store large quantities of raw data. Binaries store data in a much more space efficient manner than in lists or tuples, and the runtime system is optimized for the efficient input and output of binaries. Binaries are written and printed as sequences of integers or strings, enclosed in double less than and greater than brackets. Following is an example of binaries in Erlang − Example Live Demo -module(helloworld). -export([start/0]). start() -> io:fwrite(“~p~n”,[<<5,10,20>>]), io:fwrite(“~p~n”,[<<“hello”>>]). When we run the above program, we will get the following result. Output <<5,10,20>> <<“hello”>> Let’s look at the Erlang functions which are available to work with Binaries − Sr.No. Methods & Description 1 list_to_binary This method is used to convert an existing list to a list of binaries. 2 split_binary This method is used to split the binary list based on the index position specified. 3 term_to_binary This method is used to convert a term to binary. 4 is_binary This method is used to check if a bitstring is indeed a binary value. 5 binary_part This method is used to extract a part of the binary string 6 binary_to_float This method is used to convert a binary value to a float value. 7 binary_to_integer This method is used to convert a binary value to a integer value. 8 binary_to_list This method is used to convert a binary value to a list. 9 binary_to_atom This method is used to convert a binary value to an atom. Print Page Previous Next Advertisements ”;

Erlang – Numbers

Erlang – Numbers ”; Previous Next In Erlang there are 2 types of numeric literals which are integers and floats. Following are some examples which show how integers and floats can be used in Erlang. Integer − An example of how the number data type can be used as an integer is shown in the following program. This program shows the addition of 2 Integers. Example Live Demo -module(helloworld). -export([start/0]). start() -> io:fwrite(“~w”,[1+1]). The output of the above program will be as follows − Output 2 Float − An example of how the number data type can be used as a float is shown in the following program. This program shows the addition of 2 Integers. Example Live Demo -module(helloworld). -export([start/0]). start() -> io:fwrite(“~w”,[1.1+1.2]). The output of the above program will be as follows − Output 2.3 Displaying Float and Exponential Numbers When using the fwrite method to output values to the console, there are formatting parameters available which can be used to output numbers as float or exponential numbers. Let’s look at how we can achieve this. Example Live Demo -module(helloworld). -export([start/0]). start() -> io:fwrite(“~f~n”,[1.1+1.2]), io:fwrite(“~e~n”,[1.1+1.2]). The output of the above program will be as follows − Output 2.300000 2.30000e+0 The following key things need to be noted about the above program − When the ~f option is specified it means that the argument is a float which is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6. When the ~e option is specified it means that the argument is a float which is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6. Mathematical Functions for Numbers The following mathematical functions are available in Erlang for numbers. Note that all the mathematical functions for Erlang are present in the math library. So all of the below examples will use the import statement to import all the methods in the math library. Sr.No. Mathematical Functions & Description 1 sin This method returns the sine of the specified value. 2 cos This method returns the cosine of the specified value. 3 tan This method returns the tangent of the specified value. 4 asin The method returns the arcsine of the specified value. 5 acos The method returns the arccosine of the specified value. 6 atan The method returns the arctangent of the specified value. 7 exp The method returns the exponential of the specified value. 8 log The method returns the logarithmic of the specified value. 9 abs The method returns the absolute value of the specified number. 10 float The method converts a number to a float value. 11 Is_float The method checks if a number is a float value. 12 Is_Integer The method checks if a number is a Integer value. Print Page Previous Next Advertisements ”;

Erlang – Atoms

Erlang – Atoms ”; Previous Next An atom is a literal, a constant with name. 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 @. The following program is an example of how atoms can be used in Erlang. This program declares 3 atoms, atom1, atom_1 and ‘atom 1’ respectively. So you can see the different ways an atom can be declared. Example Live Demo -module(helloworld). -export([start/0]). start() -> io:fwrite(atom1), io:fwrite(“~n”), io:fwrite(atom_1), io:fwrite(“~n”), io:fwrite(”atom 1”), io:fwrite(“~n”). The output of the above program would be follows − Output atom1 atom_1 atom 1 Let’s see some of the methods available in Erlang to work with atoms. Sr.No. Methods and Description 1 is_atom This method is used to determine if a term is indeed an atom. 2 atom_to_list This method is used to convert an atom to a list. 3 list_to_atom This method is used to convert a list item to an atom. 4 atom_to_binary This method is used to convert an atom to a binary value. 5 binary_to_atom This method is used to convert a binary value to an atom value. Print Page Previous Next Advertisements ”;

Erlang – Functions

Erlang – Functions ”; Previous Next Erlang is known as a functional programming language, hence you would expect to see a lot of emphasis on how functions work in Erlang. This chapter covers what all can be done with the functions in Erlang. Defining a Function The syntax of a function declaration is as follows − Syntax FunctionName(Pattern1… PatternN) -> Body; Where, FunctionName − The function name is an atom. Pattern1… PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions. Body − A clause body consists of a sequence of expressions separated by comma (,): The following program is a simple example of the use of functions − Example Live Demo -module(helloworld). -export([add/2,start/0]). add(X,Y) -> Z = X+Y, io:fwrite(“~w~n”,[Z]). start() -> add(5,6). The following pointers should be noted about the above program − We are defining two functions, one is called add which takes 2 parameters and the other is the start function. Both functions are defined with the export function. If we don’t do this, we will not be able to use the function. One function can be called inside another. Here we are calling the add function from the start function. The output of the above program will be − Output 11 Anonymous Functions An anonymous function is a function, which has no name associated with it. Erlang has the facility to define anonymous functions. The following program is an example of an anonymous function. Example Live Demo -module(helloworld). -export([start/0]). start() -> Fn = fun() -> io:fwrite(“Anonymous Function”) end, Fn(). The following points need to be noted about the above example − The anonymous function is defined with the fun() keyword. The Function is assigned to a variable called Fn. The Function is called via the variable name. The output of the above program will be − Output Anonymous Function Functions with Multiple Arguments Erlang 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. In the following example, the function demo is defined with multiple arguments for each function definition. Example Live Demo -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, io:fwrite(“~w~n”,[A]). start() -> add(5,6), add(5,6,6). In the above program, we are defining the add function twice. But the definition of the first add function takes in two parameters and the second one takes in three parameters. The output of the above program will be − Output 11 17 Functions with Guard Sequences Functions in Erlang also have the capability of having guard sequences. These are nothing but expressions which only when evaluated to true will cause the function to run. The syntax of a function with a guard sequence is shown in the following program. Syntax FunctionName(Pattern1… PatternN) [when GuardSeq1]-> Body; Where, FunctionName − The function name is an atom. Pattern1… PatternN − Each argument is a pattern. The number of arguments N is the arity of the function. A function is uniquely defined by the module name, function name, and arity. That is, two functions with the same name and in the same module, but with different arities are two different functions. Body − A clause body consists of a sequence of expressions which are separated by a comma (,). GuardSeq1 − This is the expression which gets evaluated when the function is called. The following program is a simple example of the use of a function with a guard sequence. Example Live Demo -module(helloworld). -export([add/1,start/0]). add(X) when X>3 -> io:fwrite(“~w~n”,[X]). start() -> add(4). The output of the above program is − Output 4 If the add function was called as add(3), the program will result in an error. Print Page Previous Next Advertisements ”;

Erlang – Performance

Erlang – Performance ”; Previous Next When talking about performance the following points need to be noted about Erlang. Funs are very fast − Funs was given its own data type in R6B and was further optimized in R7B. Using the ++ operator − This operator needs to be used in the proper way. The following example is the wrong way to do a ++ operation. Example -module(helloworld). -export([start/0]). start()-> fun_reverse([H|T]) -> fun_reverse(T)++[H]; fun_reverse([]) -> []. As the ++ operator copies its left operand, the result is copied repeatedly, leading to quadratic complexity. Using Strings − String handling can be slow if done improperly. In Erlang, you need to think a little more about how the strings are used and choose an appropriate representation. If you use regular expressions, use the re-module in STDLIB instead of the obsolete regexp module. BEAM is a Stack-Based Byte-Code Virtual Machine − BEAM is a register-based virtual machine. It has 1024 virtual registers that are used for holding temporary values and for passing arguments when calling functions. Variables that need to survive a function call are saved to the stack. BEAM is a threaded-code interpreter. Each instruction is word pointing directly to executable C-code, making instruction dispatching very fast. Print Page Previous Next Advertisements ”;