Sophie

Sophie

distrib > Fedora > 17 > i386 > media > updates > by-pkgid > 675c8c8167236dfcf8d66da674f931e8 > files > 65

erlang-doc-R15B-03.3.fc17.noarch.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html 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 bgcolor="white" text="#000000" link="#0000ff" vlink="#ff00ff" alink="#ff0000"><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">
<img alt="Erlang logo" src="../erlang-logo.png"><br><small><a href="users_guide.html">User's Guide</a><br><a href="../pdf/otp-system-documentation-5.9.3.1.pdf">PDF</a><br><a href="../index.html">Top</a></small><p><strong>Getting Started with Erlang</strong><br><strong>User's Guide</strong><br><small>Version 5.9.3.1</small></p>
<br><a href="javascript:openAllFlips()">Expand All</a><br><a href="javascript:closeAllFlips()">Contract All</a><p><small><strong>Chapters</strong></small></p>
<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="Introduction"><a href="intro.html#id62060">Introduction</a></li>
<li title="Things Left Out"><a href="intro.html#id60748">Things Left Out</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#id62023">The Erlang Shell</a></li>
<li title="Modules and Functions"><a href="seq_prog.html#id57046">Modules and Functions</a></li>
<li title="Atoms"><a href="seq_prog.html#id57421">Atoms</a></li>
<li title="Tuples"><a href="seq_prog.html#id62855">Tuples</a></li>
<li title="Lists"><a href="seq_prog.html#id57425">Lists</a></li>
<li title="Standard Modules and Manual Pages"><a href="seq_prog.html#id63464">Standard Modules and Manual Pages</a></li>
<li title="Writing Output to a Terminal"><a href="seq_prog.html#id63511">Writing Output to a Terminal</a></li>
<li title="A Larger Example"><a href="seq_prog.html#id65303">A Larger Example</a></li>
<li title="Matching, Guards and Scope of Variables"><a href="seq_prog.html#id63164">Matching, Guards and Scope of Variables</a></li>
<li title="More About Lists"><a href="seq_prog.html#id63431">More About Lists</a></li>
<li title="If and Case"><a href="seq_prog.html#id66137">If and Case</a></li>
<li title="Built In Functions (BIFs)"><a href="seq_prog.html#id66368">Built In Functions (BIFs)</a></li>
<li title="Higher Order Functions (Funs)"><a href="seq_prog.html#id66559">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#id66869">Processes</a></li>
<li title="Message Passing"><a href="conc_prog.html#id67007">Message Passing</a></li>
<li title="Registered Process Names"><a href="conc_prog.html#id67348">Registered Process Names</a></li>
<li title="Distributed Programming"><a href="conc_prog.html#id67451">Distributed Programming</a></li>
<li title="A Larger Example"><a href="conc_prog.html#id67712">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="Timeouts"><a href="robustness.html#id68419">Timeouts</a></li>
<li title="Error Handling"><a href="robustness.html#id68545">Error Handling</a></li>
<li title="The Larger Example with Robustness Added"><a href="robustness.html#id68732">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#id68928">The Larger Example Divided into Several Files</a></li>
<li title="Header Files"><a href="record_macros.html#id69078">Header Files</a></li>
<li title="Records"><a href="record_macros.html#id69123">Records</a></li>
<li title="Macros"><a href="record_macros.html#id69217">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><a name="id68928">5.1 
        The Larger Example Divided into Several Files</a></h3>
    
    <p>To illustrate this, we will divide the messenger example from
      the previous chapter into five files.</p>
    <dl>
      <dt><strong><span class="code">mess_config.hrl</span></strong></dt>
      <dd>header file for configuration data</dd>
      <dt><strong><span class="code">mess_interface.hrl</span></strong></dt>
      <dd>interface definitions between the client and the messenger</dd>
      <dt><strong><span class="code">user_interface.erl</span></strong></dt>
      <dd>functions for the user interface</dd>
      <dt><strong><span class="code">mess_client.erl</span></strong></dt>
      <dd>functions for the client side of the messenger</dd>
      <dt><strong><span class="code">mess_server.erl</span></strong></dt>
      <dd>functions for the server side of the messenger</dd>
    </dl>
    <p>While doing this we will also clean up the message passing
      interface between the shell, the client and the server and define
      it using <strong>records</strong>, we will also introduce <strong>macros</strong>.</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 at 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) -&gt;
    case whereis(mess_client) of 
        undefined -&gt;
            register(mess_client, 
                     spawn(mess_client, client, [?server_node, Name]));
        _ -&gt; already_logged_on
    end.

logoff() -&gt;
    mess_client ! logoff.

message(ToName, Message) -&gt;
    case whereis(mess_client) of % Test if the client is running
        undefined -&gt;
            not_logged_on;
        _ -&gt; 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) -&gt;
    {messenger, Server_Node} ! #logon{client_pid=self(), username=Name},
    await_result(),
    client(Server_Node).

client(Server_Node) -&gt;
    receive
        logoff -&gt;
            exit(normal);
        #message_to{to_name=ToName, message=Message} -&gt;
            {messenger, Server_Node} ! 
                #message{client_pid=self(), to_name=ToName, message=Message},
            await_result();
        {message_from, FromName, Message} -&gt;
            io:format("Message from ~p: ~p~n", [FromName, Message])
    end,
    client(Server_Node).

%%% wait for a response from the server
await_result() -&gt;
    receive
        #abort_client{message=Why} -&gt;
            io:format("~p~n", [Why]),
            exit(normal);
        #server_reply{message=What} -&gt;
            io:format("~p~n", [What])
    after 5000 -&gt;
            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() -&gt;
    process_flag(trap_exit, true),
    server([]).

%%% the user list has the format [{ClientPid1, Name1},{ClientPid22, Name2},...]
server(User_List) -&gt;
    io:format("User list = ~p~n", [User_List]),
    receive
        #logon{client_pid=From, username=Name} -&gt;
            New_User_List = server_logon(From, Name, User_List),
            server(New_User_List);
        {'EXIT', From, _} -&gt;
            New_User_List = server_logoff(From, User_List),
            server(New_User_List);
        #message{client_pid=From, to_name=To, message=Message} -&gt;
            server_transfer(From, To, Message, User_List),
            server(User_List)
    end.

%%% Start the server
start_server() -&gt;
    register(messenger, spawn(?MODULE, server, [])).

%%% Server adds a new user to the user list
server_logon(From, Name, User_List) -&gt;
    %% check if logged on anywhere else
    case lists:keymember(Name, 2, User_List) of
        true -&gt;
            From ! #abort_client{message=user_exists_at_other_node},
            User_List;
        false -&gt;
            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) -&gt;
    lists:keydelete(From, 1, User_List).

%%% Server transfers a message between user
server_transfer(From, To, Message, User_List) -&gt;
    %% check that the user is logged on and who he is
    case lists:keysearch(From, 1, User_List) of
        false -&gt;
            From ! #abort_client{message=you_are_not_logged_on};
        {value, {_, Name}} -&gt;
            server_transfer(From, Name, To, Message, User_List)
    end.
%%% If the user exists, send the message
server_transfer(From, Name, To, Message, User_List) -&gt;
    %% Find the receiver and send the message
    case lists:keysearch(To, 2, User_List) of
        false -&gt;
            From ! #server_reply{message=receiver_not_found};
        {value, {ToPid, To}} -&gt;
            ToPid ! #message_from{from_name=Name, message=Message}, 
            From !  #server_reply{message=sent} 
    end.

%%%----END FILE---</pre></div>
  

  <h3><a name="id69078">5.2 
        Header Files</a></h3>
    
    <p>You will see some files above with extension <span class="code">.hrl</span>. These
      are header files which 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 our 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><a name="id69123">5.3 
        Records</a></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 exactly equivalent to:</p>
    <div class="example"><pre>
{message_to, To_Name, Message}</pre></div>
    <p>Creating record, is best illustrated by an example:</p>
    <div class="example"><pre>
#message_to{message="hello", to_name=fred)</pre></div>
    <p>This will create:</p>
    <div class="example"><pre>
{message_to, fred, "hello"}</pre></div>
    <p>Note that you don't 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 which are easy to change. For example, if you want to
      add a new field to the record, you will 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 will get the value of the atom undefined. (*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} -&gt;</pre></div>
    <p>is the same as:</p>
    <div class="example"><pre>
{message_to, ToName, Message}</pre></div>
  

  <h3><a name="id69217">5.4 
        Macros</a></h3>
    
    <p>The other thing we have 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>We include this file in mess_server.erl:</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>
      will now be replaced by <span class="code">messenger@super</span>.</p>
    <p>The other place a macro is used is when we spawn the server
      process:</p>
    <div class="example"><pre>
spawn(?MODULE, server, [])</pre></div>
    <p>This is a standard macro (i.e. defined by the system, not
      the user). <span class="code">?MODULE</span> is always replaced by the name of
      current module (i.e. 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 our
      case we simply have put them in the same directory which is our
      current working directory (i.e. the place we 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 could be any valid Erlang term.</p>
  
</div>
<div class="footer">
<hr>
<p>Copyright © 1996-2012 Ericsson AB. All Rights Reserved.</p>
</div>
</div>
</div></body>
</html>