Erlang has two composite structures: tuple and list. The difference between the two is that the number of child elements of tuple is fixed and cannot be changed after declaration. The list is variable, you can use [H | T] to retrieve or insert new elements. Record is a bit like a structure in C/C ++. It is actually a syntactic sugar, which facilitates our development and is converted into a tuple expression during code compilation.
Tuple
The tuple representation method is as follows:
{Term1,...,TermN}The following is an example of erlang tuple and some basic operations:
1> A = {1,2}.{1,2}2> tuple_size(A).23> is_tuple(A).true4> tuple_to_list(A).[1,2]5> element(1, A).16> setelement(2, A, 3).{1,3}
Record
Record is a bit like a structure in C/C ++. The representation method is as follows:
-record(Name, {Field1 [= Value1], ... FieldN [= ValueN]}).
The following is an example of erlang record and some basic operations:
The record structure defined in % shell is defined in the person % Equivalent Program-record (person, {name, age }). 7> rd (person, {name, age }). person8> A1 = # person {name = "john", age = 10 }. # person {name = "john", age = 10} 9> A2 = A1 # person {name = "Lucy "}. # person {name = "Lucy", age = 10 }%% record value 10> X = # person {_ = 1 }. # person {name = 1, age = 1} 11> element (2, X ). 112> setelement (2, X, "Tom "). # person {name = "Tom", age = 1}
What is the relationship between tuple and record?
Record is only the structure of the language program. It facilitates our development and will be converted to tuple during erlang compilation.
In % shell, the record structure person2 % defined in the equivalent program-record (person2, {name = "", age = 1 }). 13> rd (person2, {name = "", age = 1 }). person214> A3 = # person2 {name = "Jimmy "}. # person2 {name = "Jimmy", age = 1 }%% pattern matching 15 >{_, Name, _ }= A3. # person2 {name = "Jimmy ", age = 0} 16> Name. "Jimmy" 17> # person2 {name = Name2} = A3. # person2 {name = "Jimmy", age = 0} 18> Name2. "Jimmy"
The following is a simple example to test the assembly code of tuple and record.
-module(test).-export([test/0]).-record(person, {name, age}).test() ->A = {person, "Tom", 1},B = #person{name = "Tom", age = 1},{A,B}.
You can run the erlc-S test. erl command to generate the assembly code of test. S.
{Function, test, 0, 2 }.
{Label, 1 }.
{Line, [{location, "c:/test. erl", 7}]}.
{Func_info, {atom, test}, {atom, test}, 0 }.
{Label, 2 }.
{Move, {literal ,{{Person, "Tom", 1},{Person, "Tom", 1}}}, {X, 0 }}.
Return.
Refer:
Http://blog.csdn.net/mycwq/article/details/31421341