<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html xmlns:erl="http://erlang.org" xmlns:fn="http://www.w3.org/2005/02/xpath-functions"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../otp_doc.css" type="text/css"> <title>Erlang -- Records and Macros</title> </head> <body> <div id="container"> <script id="js" type="text/javascript" language="JavaScript" src="../js/flipmenu/flipmenu.js"></script><script id="js2" type="text/javascript" src="../js/erlresolvelinks.js"></script><script language="JavaScript" type="text/javascript"> <!-- function getWinHeight() { var myHeight = 0; if( typeof( window.innerHeight ) == 'number' ) { //Non-IE myHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' myHeight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible myHeight = document.body.clientHeight; } return myHeight; } function setscrollpos() { var objf=document.getElementById('loadscrollpos'); document.getElementById("leftnav").scrollTop = objf.offsetTop - getWinHeight()/2; } function addEvent(obj, evType, fn){ if (obj.addEventListener){ obj.addEventListener(evType, fn, true); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } } addEvent(window, 'load', setscrollpos); //--></script><div id="leftnav"><div class="innertube"> <div class="erlang-logo-wrapper"><a href="../index.html"><img alt="Erlang Logo" src="../erlang-logo.png" class="erlang-logo"></a></div> <p class="section-title">Getting Started with Erlang</p> <p class="section-subtitle">User's Guide</p> <p class="section-version">Version 10.2.3</p> <ul class="panel-sections"> <li><a href="users_guide.html">User's Guide</a></li> <li><a href="../pdf/otp-system-documentation-10.2.3.pdf">PDF</a></li> <li><a href="../index.html">Top</a></li> </ul> <ul class="expand-collapse-items"> <li><a href="javascript:openAllFlips()">Expand All</a></li> <li><a href="javascript:closeAllFlips()">Contract All</a></li> </ul> <h3>Chapters</h3> <ul class="flipMenu" imagepath="../js/flipmenu"> <li id="no" title="Introduction" expanded="false">Introduction<ul> <li><a href="intro.html"> Top of chapter </a></li> <li title="Prerequisites"><a href="intro.html#prerequisites">Prerequisites</a></li> <li title="Omitted Topics"><a href="intro.html#omitted-topics">Omitted Topics</a></li> </ul> </li> <li id="no" title="Sequential Programming" expanded="false">Sequential Programming<ul> <li><a href="seq_prog.html"> Top of chapter </a></li> <li title="The Erlang Shell"><a href="seq_prog.html#the-erlang-shell">The Erlang Shell</a></li> <li title="Modules and Functions"><a href="seq_prog.html#modules-and-functions">Modules and Functions</a></li> <li title="Atoms"><a href="seq_prog.html#atoms">Atoms</a></li> <li title="Tuples"><a href="seq_prog.html#tuples">Tuples</a></li> <li title="Lists"><a href="seq_prog.html#lists">Lists</a></li> <li title="Maps"><a href="seq_prog.html#maps">Maps</a></li> <li title="Standard Modules and Manual Pages"><a href="seq_prog.html#standard-modules-and-manual-pages">Standard Modules and Manual Pages</a></li> <li title="Writing Output to a Terminal"><a href="seq_prog.html#writing-output-to-a-terminal">Writing Output to a Terminal</a></li> <li title="A Larger Example"><a href="seq_prog.html#a-larger-example">A Larger Example</a></li> <li title="Matching, Guards, and Scope of Variables"><a href="seq_prog.html#matching,-guards,-and-scope-of-variables">Matching, Guards, and Scope of Variables</a></li> <li title="More About Lists"><a href="seq_prog.html#more-about-lists">More About Lists</a></li> <li title="If and Case"><a href="seq_prog.html#if-and-case">If and Case</a></li> <li title="Built-In Functions (BIFs)"><a href="seq_prog.html#built-in-functions--bifs-">Built-In Functions (BIFs)</a></li> <li title="Higher-Order Functions (Funs)"><a href="seq_prog.html#higher-order-functions--funs-">Higher-Order Functions (Funs)</a></li> </ul> </li> <li id="no" title="Concurrent Programming" expanded="false">Concurrent Programming<ul> <li><a href="conc_prog.html"> Top of chapter </a></li> <li title="Processes"><a href="conc_prog.html#processes">Processes</a></li> <li title="Message Passing"><a href="conc_prog.html#message-passing">Message Passing</a></li> <li title="Registered Process Names"><a href="conc_prog.html#registered-process-names">Registered Process Names</a></li> <li title="Distributed Programming"><a href="conc_prog.html#distributed-programming">Distributed Programming</a></li> <li title="A Larger Example"><a href="conc_prog.html#a-larger-example">A Larger Example</a></li> </ul> </li> <li id="no" title="Robustness" expanded="false">Robustness<ul> <li><a href="robustness.html"> Top of chapter </a></li> <li title="Time-outs"><a href="robustness.html#time-outs">Time-outs</a></li> <li title="Error Handling"><a href="robustness.html#error-handling">Error Handling</a></li> <li title="The Larger Example with Robustness Added"><a href="robustness.html#the-larger-example-with-robustness-added">The Larger Example with Robustness Added</a></li> </ul> </li> <li id="loadscrollpos" title="Records and Macros" expanded="true">Records and Macros<ul> <li><a href="record_macros.html"> Top of chapter </a></li> <li title="The Larger Example Divided into Several Files"><a href="record_macros.html#the-larger-example-divided-into-several-files">The Larger Example Divided into Several Files</a></li> <li title="Header Files"><a href="record_macros.html#header-files">Header Files</a></li> <li title="Records"><a href="record_macros.html#records">Records</a></li> <li title="Macros"><a href="record_macros.html#macros">Macros</a></li> </ul> </li> </ul> </div></div> <div id="content"> <div class="innertube"> <h1>5 Records and Macros</h1> <p>Larger programs are usually written as a collection of files with a well-defined interface between the various parts.</p> <h3><span onMouseOver="document.getElementById('ghlink-the-larger-example-divided-into-several-files-idm281472151291672').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-the-larger-example-divided-into-several-files-idm281472151291672').style.visibility = 'hidden';"><span id="ghlink-the-larger-example-divided-into-several-files-idm281472151291672" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/system/doc/getting_started/records_macros.xml#L35" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="the-larger-example-divided-into-several-files" href="#the-larger-example-divided-into-several-files">5.1 The Larger Example Divided into Several Files</a></span></h3> <p>To illustrate this, the messenger example from the previous section is divided into the following five files:</p> <ul> <li> <p><span class="code">mess_config.hrl</span></p> <p>Header file for configuration data</p> </li> <li> <p><span class="code">mess_interface.hrl</span></p> <p>Interface definitions between the client and the messenger</p> </li> <li> <p><span class="code">user_interface.erl</span></p> <p>Functions for the user interface</p> </li> <li> <p><span class="code">mess_client.erl</span></p> <p>Functions for the client side of the messenger</p> </li> <li> <p><span class="code">mess_server.erl</span></p> <p>Functions for the server side of the messenger</p> </li> </ul> <p>While doing this, the message passing interface between the shell, the client, and the server is cleaned up and is defined using <strong>records</strong>. Also, <strong>macros</strong> are introduced:</p> <div class="example"><pre>%%%----FILE mess_config.hrl---- %%% Configure the location of the server node, -define(server_node, messenger@super). %%%----END FILE----</pre></div> <div class="example"><pre>%%%----FILE mess_interface.hrl---- %%% Message interface between client and server and client shell for %%% messenger program %%%Messages from Client to server received in server/1 function. -record(logon,{client_pid, username}). -record(message,{client_pid, to_name, message}). %%% {'EXIT', ClientPid, Reason} (client terminated or unreachable. %%% Messages from Server to Client, received in await_result/0 function -record(abort_client,{message}). %%% Messages are: user_exists_at_other_node, %%% you_are_not_logged_on -record(server_reply,{message}). %%% Messages are: logged_on %%% receiver_not_found %%% sent (Message has been sent (no guarantee) %%% Messages from Server to Client received in client/1 function -record(message_from,{from_name, message}). %%% Messages from shell to Client received in client/1 function %%% spawn(mess_client, client, [server_node(), Name]) -record(message_to,{to_name, message}). %%% logoff %%%----END FILE----</pre></div> <div class="example"><pre>%%%----FILE user_interface.erl---- %%% User interface to the messenger program %%% login(Name) %%% One user at a time can log in from each Erlang node in the %%% system messenger: and choose a suitable Name. If the Name %%% is already logged in at another node or if someone else is %%% already logged in at the same node, login will be rejected %%% with a suitable error message. %%% logoff() %%% Logs off anybody at that node %%% message(ToName, Message) %%% sends Message to ToName. Error messages if the user of this %%% function is not logged on or if ToName is not logged on at %%% any node. -module(user_interface). -export([logon/1, logoff/0, message/2]). -include("mess_interface.hrl"). -include("mess_config.hrl"). logon(Name) -> case whereis(mess_client) of undefined -> register(mess_client, spawn(mess_client, client, [?server_node, Name])); _ -> already_logged_on end. logoff() -> mess_client ! logoff. message(ToName, Message) -> case whereis(mess_client) of % Test if the client is running undefined -> not_logged_on; _ -> mess_client ! #message_to{to_name=ToName, message=Message}, ok end. %%%----END FILE----</pre></div> <div class="example"><pre>%%%----FILE mess_client.erl---- %%% The client process which runs on each user node -module(mess_client). -export([client/2]). -include("mess_interface.hrl"). client(Server_Node, Name) -> {messenger, Server_Node} ! #logon{client_pid=self(), username=Name}, await_result(), client(Server_Node). client(Server_Node) -> receive logoff -> exit(normal); #message_to{to_name=ToName, message=Message} -> {messenger, Server_Node} ! #message{client_pid=self(), to_name=ToName, message=Message}, await_result(); {message_from, FromName, Message} -> io:format("Message from ~p: ~p~n", [FromName, Message]) end, client(Server_Node). %%% wait for a response from the server await_result() -> receive #abort_client{message=Why} -> io:format("~p~n", [Why]), exit(normal); #server_reply{message=What} -> io:format("~p~n", [What]) after 5000 -> io:format("No response from server~n", []), exit(timeout) end. %%%----END FILE---</pre></div> <div class="example"><pre>%%%----FILE mess_server.erl---- %%% This is the server process of the messenger service -module(mess_server). -export([start_server/0, server/0]). -include("mess_interface.hrl"). server() -> process_flag(trap_exit, true), server([]). %%% the user list has the format [{ClientPid1, Name1},{ClientPid22, Name2},...] server(User_List) -> io:format("User list = ~p~n", [User_List]), receive #logon{client_pid=From, username=Name} -> New_User_List = server_logon(From, Name, User_List), server(New_User_List); {'EXIT', From, _} -> New_User_List = server_logoff(From, User_List), server(New_User_List); #message{client_pid=From, to_name=To, message=Message} -> server_transfer(From, To, Message, User_List), server(User_List) end. %%% Start the server start_server() -> register(messenger, spawn(?MODULE, server, [])). %%% Server adds a new user to the user list server_logon(From, Name, User_List) -> %% check if logged on anywhere else case lists:keymember(Name, 2, User_List) of true -> From ! #abort_client{message=user_exists_at_other_node}, User_List; false -> From ! #server_reply{message=logged_on}, link(From), [{From, Name} | User_List] %add user to the list end. %%% Server deletes a user from the user list server_logoff(From, User_List) -> lists:keydelete(From, 1, User_List). %%% Server transfers a message between user server_transfer(From, To, Message, User_List) -> %% check that the user is logged on and who he is case lists:keysearch(From, 1, User_List) of false -> From ! #abort_client{message=you_are_not_logged_on}; {value, {_, Name}} -> server_transfer(From, Name, To, Message, User_List) end. %%% If the user exists, send the message server_transfer(From, Name, To, Message, User_List) -> %% Find the receiver and send the message case lists:keysearch(To, 2, User_List) of false -> From ! #server_reply{message=receiver_not_found}; {value, {ToPid, To}} -> ToPid ! #message_from{from_name=Name, message=Message}, From ! #server_reply{message=sent} end. %%%----END FILE---</pre></div> <h3><span onMouseOver="document.getElementById('ghlink-header-files-idm281472151271592').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-header-files-idm281472151271592').style.visibility = 'hidden';"><span id="ghlink-header-files-idm281472151271592" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/system/doc/getting_started/records_macros.xml#L251" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="header-files" href="#header-files">5.2 Header Files</a></span></h3> <p>As shown above, some files have extension <span class="code">.hrl</span>. These are header files that are included in the <span class="code">.erl</span> files by:</p> <div class="example"><pre>-include("File_Name").</pre></div> <p>for example:</p> <div class="example"><pre>-include("mess_interface.hrl").</pre></div> <p>In the case above the file is fetched from the same directory as all the other files in the messenger example. (*manual*).</p> <p>.hrl files can contain any valid Erlang code but are most often used for record and macro definitions.</p> <h3><span onMouseOver="document.getElementById('ghlink-records-idm281472151265944').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-records-idm281472151265944').style.visibility = 'hidden';"><span id="ghlink-records-idm281472151265944" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/system/doc/getting_started/records_macros.xml#L266" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="records" href="#records">5.3 Records</a></span></h3> <p>A record is defined as:</p> <div class="example"><pre>-record(name_of_record,{field_name1, field_name2, field_name3, ......}).</pre></div> <p>For example:</p> <div class="example"><pre>-record(message_to,{to_name, message}).</pre></div> <p>This is equivalent to:</p> <div class="example"><pre>{message_to, To_Name, Message}</pre></div> <p>Creating a record is best illustrated by an example:</p> <div class="example"><pre>#message_to{message="hello", to_name=fred)</pre></div> <p>This creates:</p> <div class="example"><pre>{message_to, fred, "hello"}</pre></div> <p>Notice that you do not have to worry about the order you assign values to the various parts of the records when you create it. The advantage of using records is that by placing their definitions in header files you can conveniently define interfaces that are easy to change. For example, if you want to add a new field to the record, you only have to change the code where the new field is used and not at every place the record is referred to. If you leave out a field when creating a record, it gets the value of the atom <span class="code">undefined</span>. (*manual*)</p> <p>Pattern matching with records is very similar to creating records. For example, inside a <span class="code">case</span> or <span class="code">receive</span>:</p> <div class="example"><pre>#message_to{to_name=ToName, message=Message} -></pre></div> <p>This is the same as:</p> <div class="example"><pre>{message_to, ToName, Message}</pre></div> <h3><span onMouseOver="document.getElementById('ghlink-macros-idm281472151253880').style.visibility = 'visible';" onMouseOut="document.getElementById('ghlink-macros-idm281472151253880').style.visibility = 'hidden';"><span id="ghlink-macros-idm281472151253880" class="ghlink"><a href="https://github.com/erlang/otp/edit/maint/system/doc/getting_started/records_macros.xml#L301" title="Found an issue with the documentation? Fix it by clicking here!"><span class="pencil"></span></a></span><a class="title_link" name="macros" href="#macros">5.4 Macros</a></span></h3> <p>Another thing that has been added to the messenger is a macro. The file <span class="code">mess_config.hrl</span> contains the definition:</p> <div class="example"><pre>%%% Configure the location of the server node, -define(server_node, messenger@super).</pre></div> <p>This file is included in <span class="code">mess_server.erl</span>:</p> <div class="example"><pre>-include("mess_config.hrl").</pre></div> <p>Every occurrence of <span class="code">?server_node</span> in <span class="code">mess_server.erl</span> is now replaced by <span class="code">messenger@super</span>.</p> <p>A macro is also used when spawning the server process:</p> <div class="example"><pre>spawn(?MODULE, server, [])</pre></div> <p>This is a standard macro (that is, defined by the system, not by the user). <span class="code">?MODULE</span> is always replaced by the name of the current module (that is, the <span class="code">-module</span> definition near the start of the file). There are more advanced ways of using macros with, for example, parameters (*manual*).</p> <p>The three Erlang (<span class="code">.erl</span>) files in the messenger example are individually compiled into object code file (<span class="code">.beam</span>). The Erlang system loads and links these files into the system when they are referred to during execution of the code. In this case, they are simply put in our current working directory (that is, the place you have done "cd" to). There are ways of putting the <span class="code">.beam</span> files in other directories.</p> <p>In the messenger example, no assumptions have been made about what the message being sent is. It can be any valid Erlang term.</p> </div> <div class="footer"> <hr> <p>Copyright © 1996-2019 Ericsson AB. All Rights Reserved.</p> </div> </div> </div> <script type="text/javascript">window.__otpTopDocDir = '../js/';</script><script type="text/javascript" src="../js/highlight.js"></script> </body> </html>