Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate arrays in Elixir

Tags:

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]
like image 410
steakunderscore Avatar asked Nov 02 '15 17:11

steakunderscore


2 Answers

For concatenation, there is the ++ operator.

So for the example

iex> [1, 2] ++ [3, 4]
[1, 2, 3, 4]
like image 130
steakunderscore Avatar answered Nov 14 '22 23:11

steakunderscore


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

like image 26
Gazler Avatar answered Nov 14 '22 21:11

Gazler