erlang有两种复合结构,tuple和list,两者的区别是tuple子元素的个数是固定不变的,声明后就不能改变了;而list是可变的,可以通过[H|T]来取出或插入新元素。record有点像C/C++里面的结构体,实际上是语法糖,方便我们的开发,代码汇编时转成tuple表达形式。
Tuple
tuple的表示方法如:
{Term1,...,TermN}
下面以例子说明erlang tuple及一些基本操作:
1> A = {1,2}. {1,2} 2> tuple_size(A). 2 3> is_tuple(A). true 4> tuple_to_list(A). [1,2] 5> element(1, A). 1 6> setelement(2, A, 3). {1,3}
Record
record有点像C/C++里面的结构体,表示方法如:
-record(Name, {Field1 [= Value1], ... FieldN [= ValueN]}).
下面以例子说明erlang record及一些基本操作:
%% shell下定义 record结构 person %% 等效程序里定义 -record(person, {name, age}). 7> rd(person, {name, age}). person 8> A1 = #person{name = "john", age = 10}. #person{name = "john",age = 10} 9> A2 = A1#person{name = "Lucy"}. #person{name = "Lucy",age = 10} %% record 一次赋值 10> X = #person{_ = 1}. #person{name = 1,age = 1} 11> element(2, X). 1 12> setelement(2, X, "Tom"). #person{name = "Tom",age = 1}
tuple 和 record 有什么关系?
record只是语言程序上的结构,方便我们的开发,在erlang编译的时候会转成tuple处理
%% shell下定义 record结构 person2 %% 等效程序里定义 -record(person2, {name = "", age = 1}). 13> rd(person2, {name = "", age = 1}). person2 14> A3 = #person2{name = "Jimmy"}. #person2{name = "Jimmy",age = 1} %% 模式匹配 15> {_, Name, _} = A3. #person2{name = "Jimmy",age = 0} 16> Name. "Jimmy" 17> #person2{name = Name2} = A3. #person2{name = "Jimmy",age = 0} 18> Name2. "Jimmy"
下面,以一个简单的例子,测试tuple和record的汇编代码
-module(test). -export([test/0]). -record(person, {name, age}). test() -> A = {person, "Tom", 1}, B = #person{name = "Tom", age = 1}, {A,B}.
通过命令erlc -S test.erl 可以生成 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.
参考:
http://blog.csdn.net/mycwq/article/details/31421341
说说erlang tuple和record结构
时间: 2024-10-10 09:39:40