Erlang – Tuples

Erlang – Tuples ”; Previous Next A tuple is a compound data type with a fixed number of terms. Each term in the Tuple is called an element. The number of elements is said to be the size of the Tuple. An example of how the Tuple data type can be used is shown in the following program. Here we are defining a Tuple P which has 3 terms. The tuple_size is an inbuilt function defined in Erlang which can be used to determine the size of the Tuple. Example Live Demo -module(helloworld). -export([start/0]). start() -> P = {john,24,{june,25}} , io:fwrite(“~w”,[tuple_size(P)]). The output of the above program will be as follows. Output 3 Let’s look at some more operations which are available for tuples. Sr.No. Methods & Description 1 is_tuple This method is used to determine is the term provided is indeed a tuple. 2 list_to_tuple This method is to convert a list to a tuple. 3 tuple_to_list This method is convert a tuple to a list. Print Page Previous Next Advertisements ”;

Erlang – Drivers

Erlang – Drivers ”; Previous Next Sometimes we want to run a foreign-language program inside the Erlang Runtime System. In this case, the program is written as a shared library that is dynamically linked into the Erlang runtime system. The linked-in driver appears to the programmer as a port program and obeys exactly the same protocol as for a port program. Creating a Driver Creating a linked-in driver is the most efficient way of interfacing foreign-language code with Erlang, but it is also the most dangerous. Any fatal error in the linked-in driver will crash the Erlang System. Following is an example of a driver implementation in Erlang − Example -module(helloworld). -export([start/0, stop/0]). -export([twice/1, sum/2]). start() -> start(“example1_drv” ). start(SharedLib) -> case erl_ddll:load_driver(“.” , SharedLib) of ok -> ok; {error, already_loaded} -> ok; _ -> exit({error, could_not_load_driver}) end, spawn(fun() -> init(SharedLib) end). init(SharedLib) -> register(example1_lid, self()), Port = open_port({spawn, SharedLib}, []), loop(Port). stop() -> example1_lid ! stop. twice(X) -> call_port({twice, X}). sum(X,Y) -> call_port({sum, X, Y}). call_port(Msg) -> example1_lid ! {call, self(), Msg}, receive {example1_lid, Result} -> Result end. LINKED-IN DRIVERS 223 loop(Port) -> receive {call, Caller, Msg} -> Port ! {self(), {command, encode(Msg)}}, receive {Port, {data, Data}} -> Caller ! {example1_lid, decode(Data)} end, loop(Port); stop -> Port ! {self(), close}, receive {Port, closed} -> exit(normal) end; {”EXIT”, Port, Reason} -> io:format(“~p ~n” , [Reason]), exit(port_terminated) end. encode({twice, X}) -> [1, X]; encode({sum, X, Y}) -> [2, X, Y]. decode([Int]) -> Int. Please note that working with drivers is extremely complex and care should be taken when working with drivers. Print Page Previous Next Advertisements ”;

Erlang – Ports

Erlang – Ports ”; Previous Next In Erlang, ports are used for communication between different programs. A socket is a communication endpoint that allows machines to communicate over the Internet by using the Internet Protocol (IP). Types of Protocols Used in Ports There are 2 types of protocols available for communication. One is UDP and the other is TCP. UDP lets applications send short messages (called datagrams) to each other, but there is no guarantee of delivery for these messages. They can also arrive out of order. TCP, on the other hand, provides a reliable stream of bytes that are delivered in order as long as the connection is established. Let’s look at a simple example of opening a port using UDP. Example Live Demo -module(helloworld). -export([start/0]). start() -> {ok, Socket} = gen_udp:open(8789), io:fwrite(“~p”,[Socket]). The following things need to be noted about the above program The gen_udp contains the modules in Erlang used for UDP communication. Here 8789 is the port number which is being opened in Erlang. You need to make sure this port number is available and can be used. The output of the above program is − #Port<0.376> Sending a Message on the Port Once the port has been opened a message can be sent on the port. This is done via the send method. Let’s look at the syntax and the following example. Syntax send(Socket, Address, Port, Packet) Parameters Socket − This is the socket created with the gen_udp:open command. Address − This is machine address to where the message has to be sent to. port − This is the port no on which the message needs to be sent. Packet − This is the packet or message details which needs to be sent. Return Values An ok message is returned if the message was sent properly. For example Live Demo -module(helloworld). -export([start/0]). start() -> {ok, Socket} = gen_udp:open(8789), io:fwrite(“~p”,[Socket]), io:fwrite(“~p”,[gen_udp:send (Socket,”localhost”,8789,”Hello”)]). Output The output of the above program will be as follows. #Port<0.376>ok Receiving a Message on the Port Once the port has been opened a message can also be received on the port. This is done via the recv method. Let’s look at the syntax and the following example. Syntax recv(Socket, length) Parameters Socket − This is the socket created with the gen_udp:open command. Length − This is the length of the message which needs to be received. Return Values An ok message is returned if the message was sent properly. For example -module(helloworld). -export([start/0]). start() -> {ok, Socket} = gen_udp:open(8789), io:fwrite(“~p”,[Socket]), io:fwrite(“~p”,[gen_udp:send(Socket,”localhost”,8789,”Hello”)]), io:fwrite(“~p”,[gen_udp:recv(Socket, 20)]). The Complete Program Now obviously we cannot have the same send and receive message in the same program. You need to have them defined in different programs. So let create the following code which creates a server component that listens to messages and a client component which sends messages. Example Live Demo -module(helloworld). -export([start/0,client/1]). start() -> spawn(fun() -> server(4000) end). server(Port) -> {ok, Socket} = gen_udp:open(Port, [binary, {active, false}]), io:format(“server opened socket:~p~n”,[Socket]), loop(Socket). loop(Socket) -> inet:setopts(Socket, [{active, once}]), receive {udp, Socket, Host, Port, Bin} -> io:format(“server received:~p~n”,[Bin]), gen_udp:send(Socket, Host, Port, Bin), loop(Socket) end. client(N) -> {ok, Socket} = gen_udp:open(0, [binary]), io:format(“client opened socket=~p~n”,[Socket]), ok = gen_udp:send(Socket, “localhost”, 4000, N), Value = receive {udp, Socket, _, _, Bin} -> io:format(“client received:~p~n”,[Bin]) after 2000 -> 0 end, gen_udp:close(Socket), Value. The following things need to be noted about the above program. We define 2 functions, the first is server. This will be used to listen on the port 4000. The second is the client which will be used to send the message “Hello” to the server component. The receive loop is used to read the messages sent within a define loop. Output Now you need to run the program from 2 windows. The first window will be used to run the server component by running the following code in the erl command line window. helloworld:start(). This will display the following output in the command line window. server opened socket:#Port<0.2314> Now in the second erl command line window, run the following command. Helloworld:client(“<<Hello>>”). When you issue this command, the following output will be displayed in the first command line window. server received:<<“Hello”>> Print Page Previous Next Advertisements ”;

Erlang – Concurrency

Erlang – Concurrency ”; Previous Next Concurrent programming in Erlang needs to have the following basic principles or processes. The list includes the following principles − piD = spawn(Fun) Creates a new concurrent process that evaluates Fun. The new process runs in parallel with the caller. An example is as follows − Example Live Demo -module(helloworld). -export([start/0]). start() -> spawn(fun() -> server(“Hello”) end). server(Message) -> io:fwrite(“~p”,[Message]). The output of the above program is − Output “Hello” Pid ! Message Sends a message to the process with identifier Pid. Message sending is asynchronous. The sender does not wait but continues with what it was doing. ‘!’ is called the send operator. An example is as follows − Example Live Demo -module(helloworld). -export([start/0]). start() -> Pid = spawn(fun() -> server(“Hello”) end), Pid ! {hello}. server(Message) -> io:fwrite(“~p”,[Message]). Receive…end Receives a message that has been sent to a process. It has the following syntax − Syntax receive Pattern1 [when Guard1] -> Expressions1; Pattern2 [when Guard2] -> Expressions2; … End When a message arrives at the process, the system tries to match it against Pattern1 (with possible guard Guard1); if this succeeds, it evaluates Expressions1. If the first pattern does not match, it tries Pattern2, and so on. If none of the patterns matches, the message is saved for later processing, and the process waits for the next message. An example of the entire process with all 3 commands is shown in the following program. Example Live Demo -module(helloworld). -export([loop/0,start/0]). loop() -> receive {rectangle, Width, Ht} -> io:fwrite(“Area of rectangle is ~p~n” ,[Width * Ht]), loop(); {circle, R} -> io:fwrite(“Area of circle is ~p~n” , [3.14159 * R * R]), loop(); Other -> io:fwrite(“Unknown”), loop() end. start() -> Pid = spawn(fun() -> loop() end), Pid ! {rectangle, 6, 10}. The following things need to be noted about the above program − The loop function has the receive end loop. So when a message is sent , it will processed by the receive end loop. A new process is spawned which goes to the loop function. The message is sent to the spawned process via the Pid ! message command. The output of the above program is − Output Area of the Rectangle is 60 Maximum Number of Processes In concurrency it is important to determine the maximum number of processes that are allowed on a system. You should then be able to understand how many process can execute concurrently on a system. Let’s see an example of how we can determine what is the maximum number of processes that can execute on a system. Live Demo -module(helloworld). -export([max/1,start/0]). max(N) -> Max = erlang:system_info(process_limit), io:format(“Maximum allowed processes:~p~n” ,[Max]), statistics(runtime), statistics(wall_clock), L = for(1, N, fun() -> spawn(fun() -> wait() end) end), {_, Time1} = statistics(runtime), {_, Time2} = statistics(wall_clock), lists:foreach(fun(Pid) -> Pid ! die end, L), U1 = Time1 * 1000 / N, U2 = Time2 * 1000 / N, io:format(“Process spawn time=~p (~p) microseconds~n” , [U1, U2]). wait() -> receive die -> void end. for(N, N, F) -> [F()]; for(I, N, F) -> [F()|for(I+1, N, F)]. start()-> max(1000), max(100000). On any machine which has a good processing power, both of the above max functions will pass. Following is a sample output from the above program. Maximum allowed processes:262144 Process spawn time=47.0 (16.0) microseconds Maximum allowed processes:262144 Process spawn time=12.81 (10.15) microseconds Receive with a Timeout Sometimes a receive statement might wait forever for a message that never comes. This could be for a number of reasons. For example, there might be a logical error in our program, or the process that was going to send us a message might have crashed before it sent the message. To avoid this problem, we can add a timeout to the receive statement. This sets a maximum time that the process will wait to receive a message. Following is the syntax of the receive message with a timeout specified Syntax receive Pattern1 [when Guard1] -> Expressions1; Pattern2 [when Guard2] -> Expressions2; … after Time -> Expressions end The simplest example is to create a sleeper function as shown in the following program. Example -module(helloworld). -export([sleep/1,start/0]). sleep(T) -> receive after T -> true end. start()-> sleep(1000). The above code will sleep for 1000 Ms before actually exiting. Selective Receive Each process in Erlang has an associated mailbox. When you send a message to the process, the message is put into the mailbox. The only time this mailbox is examined is when your program evaluates a receive statement. Following is the general syntax of the Selective receive statement. Syntax receive Pattern1 [when Guard1] -> Expressions1; Pattern2 [when Guard1] -> Expressions1; … after Time -> ExpressionTimeout end This is how the above receive statement works − When we enter a receive statement, we start a timer (but only if an after section is present in the expression). Take the first message in the mailbox and try to match it against Pattern1, Pattern2, and so on. If the match succeeds, the message is removed from the mailbox, and the expressions following the pattern are evaluated. If none of the patterns in the receive statement matches the first message in the mailbox, then the first message is removed from the mailbox and put into a “save queue.” The second message in the mailbox is then tried. This procedure is repeated until a matching message is found or until all the messages in the mailbox have been examined. If none of the messages in the mailbox matches, then the process is suspended and will be rescheduled for execution the next time a new message is put in the mailbox. Note that when a new message arrives, the messages in the save queue are not rematched; only the new message is matched. As soon as a message has been matched, then all messages that have been put into the save queue are reentered into the mailbox in the order in which they arrived at the process. If a timer was set,

Erlang – Databases

Erlang – Databases ”; Previous Next Erlang has the ability to connect to the traditional databases such as SQL Server and Oracle. Erlang has an inbuilt odbc library that can be used to work with databases. Database Connection In our example, we are going to make use of the Microsoft SQL Server. Before connecting to a Microsoft SQL Server database, make sure that the following pointers are checked. You have created a database TESTDB. You have created a table EMPLOYEE in TESTDB. This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID “testuser” and password “test123” are set to access TESTDB. Ensure that you have created an ODBC DSN called usersqlserver which creates an ODBC connection to the database Establishing a Connection To establish a connection to the database, the following code example can be used. Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect(“DSN = usersqlserver;UID = testuser;PWD = test123”, []), io:fwrite(“~p”,[Ref]). The output of the above program is as follows − Output <0.33.0> The following things need to be noted about the above program. The start method of the odbc library is used to indicate the beginning of the database operation. The connect method requires a DSN, user name and password to connect. Creating a Database Table The next step after connecting to the database is to create the tables in our database. The following example shows how to create a table in the database using Erlang. Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect(“DSN = usersqlserver; UID = testuser;PWD = test123, []), odbc:sql_query(Ref, “CREATE TABLE EMPLOYEE (FIRSTNAME char varying(20), LASTNAME char varying(20), AGE integer, SEX char(1), INCOME integer)”) If you now check the database, you will see that a table called EMPLOYEE will be created. Inserting a Record into the Database It is required when you want to create your records into a database table. The following example will insert a record in the employee table. If the table is successfully updated, the record and the statement will return the value of the updated record and the number of records that were updated. Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect(“DSN = usersqlserver; UID = testuser;PWD = test123”, []), io:fwrite(“~p”,[odbc:sql_query(Ref, “INSERT INTO EMPLOYEE VALUES(”Mac”, ”Mohan”, 20, ”M”, 2000)”)]). The output of the above program will be − Output {updated,1} Fetching Records from the Database Erlang also has the capability to fetch records from the database. This is done via the sql_query method. An example is shown in the following program − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect(“DSN = usersqlserver; UID = testuser;PWD = test123”, []), io:fwrite(“~p”,[odbc:sql_query(Ref, “SELECT * FROM EMPLOYEE”) ]). The output of the above program will be as follows − Output {selected,[“FIRSTNAME”,”LASTNAME”,”AGE”,”SEX”,”INCOME”], [{“Mac”,”Mohan”,20,”M”,2000}]} So you can see that the insert command in the last section worked and the select command returned the right data. Fetching Records from the Database Based on Parameters Erlang also has the capability to fetch records from the database based on certain filter criteria. An example is as follows − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect(“DSN=usersqlserver; UID=testuser;PWD=test123”, []), io:fwrite(“~p”,[ odbc:param_query(Ref, “SELECT * FROM EMPLOYEE WHERE SEX=?”, [{{sql_char, 1}, [“M”]}])]). The output of the above program will be − Output {selected,[“FIRSTNAME”,”LASTNAME”,”AGE”,”SEX”,”INCOME”], [{“Mac”,”Mohan”,20,”M”,2000}]} Updating Records from the Database Erlang also has the capability to update records from the database. An example for the same is as follows − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect(“DSN = usersqlserver; UID = testuser;PWD = test123”, []), io:fwrite(“~p”,[ odbc:sql_query(Ref, ” UPDATE EMPLOYEE SET AGE = 5 WHERE INCOME= 2000″)]). The output of the above program will be − Output {updated,1} Deleting Records from the Database Erlang also has the capability to delete records from the database. An example for the same is as follows − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect(“DSN = usersqlserver; UID = testuser;PWD = test123”, []), io:fwrite(“~p”,[ odbc:sql_query(Ref, “DELETE EMPLOYEE WHERE INCOME= 2000”)]). The output of the above program will be as follows − Output {updated,1} Table Structure Erlang also has the capability to describe a table structure. An example is as follows − Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect(“DSN = usersqlserver; UID = testuser;PWD = test123”, []), io:fwrite(“~p”,[odbc:describe_table(Ref, “EMPLOYEE”)]). The output of the above program will be as follows − Output {ok,[{“FIRSTNAME”,{sql_varchar,20}}, {“LASTNAME”,{sql_varchar,20}}, {“AGE”,sql_integer}, {“SEX”,{sql_char,1}}, {“INCOME”,sql_integer}]} Record Count Erlang also has the capability to fetch the total count of the records in a table. An example for the same is shown in the following program. Example -module(helloworld). -export([start/0]). start() -> odbc:start(), {ok, Ref} = odbc:connect(“DSN = usersqlserver; UID = sa;PWD = demo123”, []), io:fwrite(“~p”,[odbc:select_count(Ref, “SELECT * FROM EMPLOYEE”)]). The output of the above program will be − {ok,1} Print Page Previous Next Advertisements ”;

Erlang – Funs

Erlang – Funs ”; Previous Next Funs are used to define anonymous functions in Erlang. The general syntax of an anonymous function is given below − Syntax F = fun (Arg1, Arg2, … ArgN) -> … End Where F − This is the variable name assigned to the anonymous function. Arg1, Arg2, … ArgN − These are the arguments which are passed to the anonymous function. The following example showcases how the anonymous function can be used. Example Live Demo -module(helloworld). -export([start/0]). start() -> A = fun() -> io:fwrite(“Hello”) end, A(). The following things need to be noted about the above program. The anonymous function is assigned to the variable A. The anonymous function via the variable A(). When we run the above program we will get the following result. “Hello” Another example of anonymous function is as follows, but this is with the use of parameters. Live Demo -module(helloworld). -export([start/0]). start() -> A = fun(X) -> io:fwrite(“~p~n”,[X]) end, A(5). When we run the above program we will get the following result. Output 5 Using Variables The Anonymous function have the ability to access the variables which are outside of the scope of the anonymous function. Let’s look at an example of this − Example Live Demo -module(helloworld). -export([start/0]). start() -> B = 6, A = fun(X) -> io:fwrite(“~p~n”,[X]), io:fwrite(“~p~n”,[B]) end, A(5). The following things need to be noted about the above program. The variable B is outside of the scope of the anonymous function. The anonymous function can still access the variable defined in the global scope. When we run the above program we will get the following result. Output 5 6 Functions within Functions One of the other most powerful aspects of higher order functions, is that you can define a function within a function. Let’s see an example of how we can achieve this. Example Live Demo -module(helloworld). -export([start/0]). start() -> Adder = fun(X) -> fun(Y) -> io:fwrite(“~p~n”,[X + Y]) end end, A = Adder(6), A(10). The following things need to be noted about the above program. Adder is a higher order function defined as fun(X). The Adder function fun(X) has a reference to another function fun(Y). When we run the above program we will get the following result. Output 16 Print Page Previous Next Advertisements ”;

Erlang – Lists

Erlang – Lists ”; Previous Next The List is a structure used to store a collection of data items. In Erlang, Lists are created by enclosing the values in square brackets. Following is a simple example of creating a list of numbers in Erlang. Example Live Demo -module(helloworld). -export([start/0]). start() -> Lst1 = [1,2,3], io:fwrite(“~w~n”,[Lst1]). The output of the above example will be − Output [1 2 3] Let us now discuss the various methods available for Lists. Note that the lists library needs to be imported for these methods to work. Sr.No Method and Description 1 all Returns true if Pred(Elem) returns true for all elements Elem in List, otherwise false. 2 any Returns true if Pred(Elem) returns true for at least one element Elem in List. 3 append Returns a new list List3 which is made from the elements of List1 followed by the elements of List2. 4 delete Deletes an element from the list and returns a new list. 5 droplast Drops the last element of a List. 6 duplicate Returns a list which contains N copies of the term Elem 7 last Returns the last element of the list 8 max Returns the element of the list which has the maximum value. 9 member Checks if an element is present in the list or not. 10 min Returns the element of the list which has the minimum value. 11 merge Returns the sorted list formed by merging all the sub-lists of ListOfLists. 12 nth Returns the Nth element of List. 13 nthtail Returns the Nth tail of the List. 14 reverse Reverses a list of elements. 15 sort Sorts a list of elements. 16 sublist Returns a sublist of elements. 17 sum Returns the sum of elements in the list. Print Page Previous Next Advertisements ”;

Erlang – OTP

Erlang – OTP ”; Previous Next OTP stands for Open Telecom Platform. It’s an application operating system and a set of libraries and procedures used for building large-scale, fault-tolerant, distributed applications. If you want to program your own applications using OTP, then the central concept that you will find very useful is the OTP behavior. A behavior encapsulates common behavioral patterns — think of it as an application framework that is parameterized by a callback module. The power of OTP comes from the properties such as fault tolerance, scalability, dynamic-code upgrade, and so on, can be provided by the behavior itself. So the first basic concept is to create a server component that mimics the basics of an OTP environment, let’s look at the following example for the same. Example -module(server). -export([start/2, rpc/2]). start(Name, Mod) -> register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)). rpc(Name, Request) -> Name ! {self(), Request}, receive {Name, Response} -> Response end. loop(Name, Mod, State) -> receive {From, Request} -> {Response, State1} = Mod:handle(Request, State), From ! {Name, Response}, loop(Name, Mod, State1) end. The following things need to be noted about the above program − The process if registered with the system using the register function. The process spawns a loop function which handles the processing. Now let’s write a client program that will utilize the server program. Example -module(name_server). -export([init/0, add/2, whereis/1, handle/2]). -import(server1, [rpc/2]). add(Name, Place) -> rpc(name_server, {add, Name, Place}). whereis(Name) -> rpc(name_server, {whereis, Name}). init() -> dict:new(). handle({add, Name, Place}, Dict) -> {ok, dict:store(Name, Place, Dict)}; handle({whereis, Name}, Dict) -> {dict:find(Name, Dict), Dict}. This code actually performs two tasks. It serves as a callback module that is called from the server framework code, and at the same time, it contains the interfacing routines that will be called by the client. The usual OTP convention is to combine both functions in the same module. So here is how the above program needs to be run − In erl, first run the server program by running the following command. server(name_server,name_server) You will get the following output − Output true Then, run the following command name_server.add(erlang,”Tutorialspoint”). You will get the following output − Output Ok Then, run the following command − name_server.whereis(erlang). You will get the following output − Output {ok,”Tutorialspoint”} Print Page Previous Next Advertisements ”;

Erlang – Header Files

Erlang – Header Files ”; Previous Next Header files are like include files in any other programming language. It is useful for splitting modules into different files and then accessing these header files into separate programs. To see header files in action, let’s look at one of our earlier examples of records. Let’s first create a file called user.hrl and add the following code − -record(person, {name = “”, id}). Now in our main program file, let’s add the following code − Example -module(helloworld). -export([start/0]). -include(“user.hrl”). start() -> P = #person{name = “John”,id = 1}, io:fwrite(“~p~n”,[P#person.id]), io:fwrite(“~p~n”,[P#person.name]). As you can see from the above program, we are actually just including the user.hrl file which automatically inserts the –record code in it. If you execute the above program, you will get the following output. Output 1 “John” You can also do the same thing with macros, you can define the macro inside the header file and reference it in the main file. Let’ see an example of this − Let’s first create a file called user.hrl and add the following code − -define(macro1(X,Y),{X+Y}). Now in our main program file, let’s add the following code − Example -module(helloworld). -export([start/0]). -include(“user.hrl”). start() -> io:fwrite(“~w”,[?macro1(1,2)]). If you execute the above program, you will get the following output − Output {3} Print Page Previous Next Advertisements ”;

Erlang – Pattern Matching

Erlang – Pattern Matching ”; Previous Next Patterns look the same as terms – they can be simple literals like atoms and numbers, compound like tuples and lists, or a mixture of both. They can also contain variables, which are alphanumeric strings that begin with a capital letter or underscore. A special “anonymous variable”, _ (the underscore) is used when you don”t care about the value to be matched, and won”t be using it. A pattern matches if it has the same “shape” as the term being matched, and atoms encountered are the same. For example, the following matches succeed − B = 1. 2 = 2. {ok, C} = {ok, 40}. [H|T] = [1, 2, 3,4]. Note that in the fourth example, the pipe (|) signifying the head and tail of the list as described in Terms. Also note that the left hand side should match the right hand side which is the normal case for patterns. The following examples of pattern matching will fail. 1 = 2. {ok, A} = {failure, “Don”t know the question”}. [H|T] = []. In the case of the pattern-matching operator, a failure generates an error and the process exits. How this can be trapped and handled is covered in Errors. Patterns are used to select which clause of a function will be executed. Print Page Previous Next Advertisements ”;