Record and macro in Erlang

Source: Internet
Author: User

Http://www.cnblogs.com/me-sa/archive/2011/07/20/erlang0006.html

Using tuple in Erlang, the order \ Number of data items is determined, and once the data item order is adjusted or the field is added or subtracted, it is easy to appear badmatch.

At the same time some constants if hard-coded into the code, once the value changes, it is difficult to replace all reliable replacement values.

These two data-plane changes, the corresponding solution in Erlang, are: record Macro

Record

In the code we create a record:-record (man, {name, age=0, school}).

2012-6-13 16:11:04 Update

Note that the following code is a snippet of code intercepted from the Erl file, if you want to use the record in an Erlang shell, see: [Erlang 0027] using record in Erlang shell

Let's look at the default values for the corresponding fields by using the following code:

%see Default Value

m= #man {},

Io:format ("M is: ~p ~n", [M]),

You can see that the value of output m is: {man,undefined,0,undefined}, in fact, from here we can see whether the record is implemented within Erlang or a tuple.

From the point of view of pure data we find {man,undefined,0,undefined}==m, but the record itself as a data abstraction mechanism, we do not directly record the tuple value form.

We assign values to specific fields, and then look at:

m2= #man {name= "Zen", age=23, school = "No.14"}, Io:format ("M2 is: ~p ~n", [M2]),

The output is M2 are: {man, "Zen", "No.14"}

With M2 data as a template, you can generate a new record:

M3 = m2#man{name= "tt", age=24}, Io:format ("M3 is: ~p ~n", [M3]),

The result is: M3 are: {man, "tt", "No.14"}

You can also use data templates like this:

Birthday (M) when Is_record (M,man), M#man{age=m#man.age +1}.

2012-10-15 14:39:43 Update

Blog Park-Beach 14:07:08
There is a list of the record, whose field is a,b,c, for example {user,a,b,c}, now want to use its list to generate another record of the list, whose field is {user1,b,c}, how to write the most convenient
User1 is a field less than user.
Strong ☆2002 14:39:00
Eshell V5.9  (abort with ^g) 1> Rd (U1,{a,b,c}) .u12> Rd (U2,{b,c}) .u23> users=[#u1 {a=12,b= "Ligaoren", c=true }, #u1 {a=23,b= "Zen", C=false}]. [#u1 {a = 12,b = "Ligaoren", C = true}, #u1 {a = 23,b = "Zen", C = false}]4> [begin #u1 {b=b,c=c}=u, #u2 {b=b,c=c} end| | U<-users]. [#u2 {b = "Ligaoren", C = true}, #u2 {b = "Zen", C = false}]5>  

The following example shows how to take a value:

M4 = #man {name= "Tt2", Age=m3#man.age}, Io:format ("M4 is: ~p ~n", [M4]),

The result is: M4 are: {man, "Tt2", 24,undefined}

We tried to nest a record to man, and we extended the name field:

-record (name, {firstname,lastname}).

We use M2 as the data template to generate the M5, while attempting to take the value of FirstName:

M5 =m2#man{name= #name {firstname= "K", lastname= "J"},age=24}, Io:format ("M5 is: ~p ~n", [M5]),

Io:format ("M5 FirstName is: ~p ~n", [M5#man.name#name.firstname])

Matches are ubiquitous in Erlang, and we can extract the values of some fields in a matching way when we use the record:

For example, this method:

Show2 (#man {name =name, age =age} = m) while Is_record (M, man)

Io:format ("Name: ~p Age: ~p ~n", [Name, Age]).

This method is extracted from the location of the entrance name and age, note that only M is the record man, so we have added a Guard:is_record (M, man)

Here are some general operations on the record, and I'll have some questions: How does Erlang judge the fact that we often encounter badrecord errors in the actual use of the record?

How do the same Is_record be judged? To know this answer requires recompiling our test file, adding a compile option, using the following method in the Erlang shell:

C (test,[' E ']). This will generate a test in the same directory. e file, open this file, all enlightened, we take M3 = M2#man{name= "tt", age=24},

Io:format ("M3 is: ~p ~n", [M3]), for example, the compiled code is:

    M3 =
Begin
REC1 = M2,
Case REC1 of
{MAN,REC2,REC3,REC4}% is judged by the way a tuple is matched
{man, "tt", 24,REC4};
_,
Error ({Badrecord,man})
End
End
Io:format ("M3 is : ~p ~n", [M3]),

And look at the corresponding code generated by the Show2 generation:

Show2 ({man,name,age,_} = {Man,_,_,_} = M) When True--Io:format ("Name: ~p Age: ~p ~n", [Name,age]).

Here is a match to the value that will affect our reading, we simplify it:

Show (M) when Is_record (M, man), Io:format ("Show M: ~p ~n", [M]).

The code it compiles is:

Show ({man,_,_,_} = M) when True

Io:format ("Show M: ~p ~n", [M]).

Macro

It's hard to imagine how hard it is to read our Erlang code without a macro, with magic number everywhere; simply summarize the use of macros in Erlang:

  1. Macro constants such as-define (TIMEOUT, 1000). -define (Servername,my_first_game_server).
  2. With macros such as:-define (Eq (x, y), x=:=y).
    -define (P (Content), OK).
  3. Conditional macros
    -ifdef (product).
    -define (who, "Product_db_adm").
    -else.
    -define (who, "Test_db_adm").
    -endif.
  4. Global macro:? Machine (VM name)
    ? Line current lines of code
    ? File Current code files
    And what's the most familiar? Module Current Modules
    There is also a macro that is more commonly used in output debugging information:
    -define (VALUE (call), Io:format ("~p = ~p~n", [?? Call,call]).
    Test1 ()? VALUE (Length ([+)]).

    2012-07-16 Update
  5. {D,macro}{D,macro,value}

    Defines a macro macro to has the value value. The default is true.

    Example:

    -module (M) ....-ifdef (Debug).-define (LOG (X), Io:format ("{~p,~p}: ~p~n", [? MODULE,? Line,x]).-else.-define (LOG (X), true).-endif ....

    When trace output is desired, debug should are defined when the module M is compiled:

    % Erlc-ddebug m.erlor1> C (M, {d, debug}). {Ok,m}


    Official document Address: http://www.erlang.org/doc/man/compile.html

    Http://www.erlang.org/doc/reference_manual/macros.html

Conditional macros can be compiled by the way the option to switch whether the production environment version or debug version, production environment to screen out the debug output can be easily implemented;

In the same way we can look at the macro and just use C (test,[' P ') when compiling. Here's an example of using a macro, guess what it was after it was compiled?

-module (MAC).

-export ([dump/1,go/1,show/2,len/1,say/0]).

-define (func,x).
-define (double,*2).
-define (F,dump (X)).
-define (Eq (x, y), x=:=y).
%-define (P (Content), OK).
-define (PF (Content,args), Io:format (Content,args)).
-define (P (content), Io:format (content)).

-define (call), Io:format ("~p=~p ~n", [?? Call,call]).

-ifdef (Me).
-define (who, "ABCD").
-else.
-define (who, "Zen").
-endif.

Say ()
? P (? WHO).


Len (list) when is_list (list)
? Len (List).

Dump (X)
? Func? Double.

Go (X)
? F.

Show (x, y) when? Eq (x, y)
? P ("They is Equal. ~n ");
Show (_x,_y)
Io:format ("HAHA").


-module (MAC).

-export ([dump/1,go/1,show/2,len/1,say/0]).

-define (func,x).
-define (double,*2).
-define (F,dump (X)).
-define (Eq (x, y), x=:=y).
%-define (P (Content), OK).
-define (PF (Content,args), Io:format (Content,args)).
-define (P (content), Io:format (content)).

-define (call), Io:format ("~p=~p ~n", [?? Call,call]).

-ifdef (Me).
-define (who, "ABCD").
-else.
-define (who, "Zen").
-endif.



Say ()
? P (? WHO).


Len (list) when is_list (list)
? Len (List).



Dump (X)
? Func? Double.

Go (X)
? F.

Show (x, y) when? Eq (x, y)
? P ("They is Equal. ~n ");
Show (_x,_y)
Io:format ("HAHA").

The generated P file is here:

-file ("./mac.erl", 1).

-module (MAC).

-export ([dump/1,go/1,show/2,len/1,say/0]).

Say ()
Io:format ("Zen").

Len (list) when is_list (list)
Io:format ("~p=~p ~n", ["Length (list)", Length (list)]).

Dump (X)
X * 2.

Go (X)
Dump (X).

Show (x, Y) when x =:= Y
Io:format ("They is Equal. ~n ");
Show (_x, _y)
Io:format ("HAHA").


-file ("./mac.erl", 1).

-module (MAC).

-export ([dump/1,go/1,show/2,len/1,say/0]).

Say ()
Io:format ("Zen").

Len (list) when is_list (list)
Io:format ("~p=~p ~n", ["Length (list)", Length (list)]).

Dump (X)
X * 2.

Go (X)
Dump (X).

Show (x, Y) when x =:= Y
Io:format ("They is Equal. ~n ");
Show (_x, _y)
Io:format ("HAHA").

In the project, these record macro is often placed in the Hrl file, through the emakefile to compile custom, this before we discussed do not repeat, click here to view;

Record and macro in Erlang

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.