Erlang: “prepending” an element to a tuple

本秂侑毒 提交于 2019-12-12 10:40:26

问题


Is it possible to write a faster equivalent to this function?

prepend(X, Tuple) ->
  list_to_tuple([X | tuple_to_list(Tuple)]).

回答1:


As prepending an element is the same as inserting it at position 1, you can use the built-in function erlang:insert_element/3:

> erlang:insert_element(1, {a, b}, z).
{z,a,b}

This function was added in Erlang/OTP R16A.




回答2:


It looks to me like that sort of thing is discouraged. If you want a list, use one.

Getting Started with Erlang:

Tuples have a fixed number of things in them.



回答3:


If you have a finite number of possible tuple lengths, you could do this:

prepend(X, {}) -> {X};
prepend(X, {A}) -> {X, A};
prepend(X, {A, B}) -> {X, A, B};
prepend(X, {A, B, C}) -> {X, A, B, C}.

You can continue this pattern for as long as you need.



来源:https://stackoverflow.com/questions/3936613/erlang-prepending-an-element-to-a-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!