Reputation: 429
I want to store coordinates in my application. A coordinate consists of three floats: x, y, and z. Is it a better practice to define a type to group them together or to define a record? The Erlang User's Guide says they are both translated to tuple expressions during compilation. Does one method have an advantage over the other?
-type coordinate() :: {X, Y, Z}.
-record(coordinate, {x, y, z}).
Upvotes: 1
Views: 114
Reputation: 3509
I guess that you mean record
s vs tuple
s, as -type
does not exist in compiled code, it's used only for type checking (and you can create types for records too).
Records are tuples with the name of the record prepended:
-record(coordinate, {x,y,z}).
#coordinate{1,2,3} == {coordinate,1,2,3}.
This new element has a minimal cost that may have some impact in your performance (it makes the record one word larger), but if you reach the point where you consider this optimization, you may optimize it further by using the components directly or rewriting the critical path in C/C++.
On the other hand, using records improves legibility a lot, and allows you to have default initializers.
I'd advise to use records for the top-level tuple for any meaningful structured value, and types for everything:
-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]).
Upvotes: 6