Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: "prepending" an element to a tuple

Tags:

erlang

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

prepend(X, Tuple) ->
  list_to_tuple([X | tuple_to_list(Tuple)]).
like image 445
Alexey Romanov Avatar asked Oct 14 '10 19:10

Alexey Romanov


Video Answer


2 Answers

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.
like image 98
nmichaels Avatar answered Oct 06 '22 20:10

nmichaels


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.

like image 30
Greg Hewgill Avatar answered Oct 06 '22 20:10

Greg Hewgill