使用类型比记录有优势吗?

xDa*_*ehh 1 erlang

我想在我的应用程序中存储坐标。坐标由三个浮点数组成:x、y 和 z。定义一个类型来将它们组合在一起或定义一个记录是更好的做法吗?Erlang 用户指南说它们在编译期间都被翻译成元组表达式。一种方法比另一种方法有优势吗?

-type coordinate() :: {X, Y, Z}.

-record(coordinate, {x, y, z}).
Run Code Online (Sandbox Code Playgroud)

Jos*_*é M 6

我猜你的意思是records vs tuples,因为-type在编译代码中不存在,它只用于类型检查(你也可以为记录创建类型)。

记录是带有记录名称的元组:

-record(coordinate, {x,y,z}).

#coordinate{1,2,3} == {coordinate,1,2,3}.
Run Code Online (Sandbox Code Playgroud)

这个新元素的成本最低,可能会对您的性能产​​生一些影响(它使记录大一个字),但如果您达到考虑此优化的程度,您可以通过直接使用组件或重写C/C++ 中的关键路径。

另一方面,使用记录可以大大提高易读性,并允许您拥有默认的初始值设定项。

我建议将顶级元组的记录用于任何有意义的结构化值,并为所有类型使用:

-record(coordinate, {
  x = 0 :: number(),
  y = 0 :: number(),
  z = 0 :: number()
 }).
-type coordinate() :: #coordinate{}.

-opaque stack(ElementType) :: {Elements :: [ElementType], Size :: non_neg_integer()}.
-record(position, {
  coord = #coordinate{} :: coordinate(),
  stack = {[], 0} :: stack(term()),
  id = 0 :: non_neg_integer()
 }).
-type position() :: #position{stack :: stack(coordinate())}.

-export_type([coordinate/0, stack/1, position/0]).

Run Code Online (Sandbox Code Playgroud)