增加 Erlang 中元组的长度

Increasing the length of a tuple in Erlang

如何在 Erlang 中增加元组的长度?例如,假设 Tup={1,2,3},现在我想向其中添加另一个元素。有什么办法吗?

元组不是灵活的数据结构。如果您经常调整它的大小,那么您应该考虑使用其他 erlang data structures like lists, maps or sets - depends on your expectation. Here is nice introduction to key-value stores.

但是如果你真的必须扩展那个元组,那么你可以使用erlang:append_element/2

{1,2,3,4} = erlang:append_element({1,2,3}, 4).

元组不可变,因此严格来说,您不能增加长度。

一般来说,如果你想要一个可变数量的数据类型,元组会很不方便。例如,迭代一个列表的所有元素是非常惯用的,而迭代一个在编译时大小未知的元组的所有元素是一件痛苦的事情。

但是,一种常见的模式是从某个函数和该元组的 return 个元素加上附加项得到一个元组。

country_coords(Name) ->
    {Lat, Lng} = find_address(Name),
    {_Street, _City, _Zip, Country} = geocode(Lat, Lng),
    {ok, Lat, Lng, Country}.

erlang:append_element(tuple_whose_length_to_increase, element_to_be)。这是内置函数,但元组、列表并不意味着 flexible.So 避免使用此函数,除非没有别的办法