9

How do I concatenate arrays in Elixir?

If I have two arrays:

[1, 2]

and

[3, 4]

how do I concatenate them to be:

[1, 2, 3, 4]
steakunderscore
  • 1,076
  • 9
  • 18

3 Answers3

25

For concatenation, there is the ++ operator.

So for the example

iex> [1, 2] ++ [3, 4]
[1, 2, 3, 4]
steakunderscore
  • 1,076
  • 9
  • 18
  • 4
    Additionally, you can also remove parts of lists with `--`, `[1, 2, 3, 4, 5] -- [3, 4, 5]` yields `[1, 2]`. – Graham S. Nov 02 '15 at 18:42
16

You can concatenate lists (not arrays) with the ++/2 function.

However often in functional programming you will build up a list using the cons (|) operator like so:

a = []              # []
b = ["foo" | a]     # ["foo"]         ["foo" | []]
c = ["bar" | b]     # ["bar", "foo"]  ["bar" | ["foo" | []]]

This is equivalent:

a = []              #  []
b = ["foo" | a]     #  ["foo" | []]
c = ["bar" | b]     #  ["bar" | ["foo" | []]]

You may well have seen this operator in pattern matching:

["bar" | tail] = ["bar", "foo"] #tail is now ["foo"]

You will often see lists built using this technique and then reversed at the end of the function call to get the results in the same order as using list concatenation (For example Enum.filter/2). This answer explains it well Erlang: Can this be done without lists:reverse?

You can read more about the list data type at http://elixir-lang.org/getting-started/basic-types.html#lists-or-tuples

Community
  • 1
  • 1
Gazler
  • 83,029
  • 18
  • 279
  • 245
  • Good point to make sure that the person who asked the question realizes that he (indefinite pronoun sense) is dealing with lists rather than arrays. – Onorio Catenacci Nov 03 '15 at 14:42
  • 1
    At the time of writing the question I did not understand this, but obviously now I do. Being that it's a fundamental part of Elixir, others are bound to ask the same question as I did. This answer addresses both the solution, and that it's not actually arrays that are being asked about. – steakunderscore Nov 06 '15 at 09:33
0

If you want to do this within pipe operator use [1, 2] |> Enum.concat([3, 4]), or another variant [1, 2] |> Kernel.++([3, 4])

Denys Klymenko
  • 394
  • 5
  • 18