steakunderscore
steakunderscore

Reputation: 1116

Concatenate arrays in Elixir

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]

Upvotes: 10

Views: 9916

Answers (3)

Denys Klymenko
Denys Klymenko

Reputation: 413

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

Upvotes: 1

Gazler
Gazler

Reputation: 84140

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

Upvotes: 15

steakunderscore
steakunderscore

Reputation: 1116

For concatenation, there is the ++ operator.

So for the example

iex> [1, 2] ++ [3, 4]
[1, 2, 3, 4]

Upvotes: 25

Related Questions