问题
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