Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate tuples in elixir

Tags:

elixir

In elixir, we can concatenate, lists like so

 ex(52)> [1,2,3,4] ++ [5,6,7]
 [1, 2, 3, 4, 5, 6, 7]

Can we also concatenate tuples? Something like this?

iex(53)> {1,2,3,4} ++ {5,6,7}
 ** (ArgumentError) argument error
    :erlang.++({1, 2, 3, 4}, {5, 6, 7})

The only other thing I can think of is to convert a tuple to list, then convert back to tuple using the to_list and to_tuple functions. But that's way too clumsy.

like image 383
User314159 Avatar asked Feb 05 '15 22:02

User314159


1 Answers

You can't concatenate tuples.

The only reason is that you are not supposed to use them as such. Most of tuple usage requires knowing their size and things get blurrier if you can concatenate them. Furthermore, concatenating tuples requires copying both tuples in memory, which is not efficient.

In other words, if you want to concatenate tuples, you may have the wrong data structure. You have two options:

  1. Use lists
  2. Compose the tuples: instead of a ++ b, just write {a, b}
like image 182
José Valim Avatar answered Oct 01 '22 13:10

José Valim