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]
For concatenation, there is the ++
operator.
So for the example
iex> [1, 2] ++ [3, 4]
[1, 2, 3, 4]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With