Add new element to list
I was trying to add a new element into a list as follow:
iex(8)> l = [3,5,7,7,8] ++ 3
[3, 5, 7, 7, 8 | 3]
iex(9)> l
[3, 5, 7, 7, 8 | 3]
Why did I get on the 5th position like
8 | 3
What it does mean?
And how can I add new element to the list?
--------Update--------
I try to loop the list as follow:
iex(2)> l = [1,2] ++ 3
[1, 2 | 3]
iex(3)> Enum.each(l, fn(x) -> IO.puts(x) end)
1
2
** (FunctionClauseError) no function clause matching in Enum."-each/2-lists^foreach/1-0-"/2
(elixir) lib/enum.ex:604: Enum."-each/2-lists^foreach/1-0-"(#Function<6.54118792/1 in :erl_eval.expr/5>, 3)
(elixir) lib/enum.ex:604: Enum.each/2
Since the pointer of the number 2 is not pointing to a list, rather to value 3, how can I loop the list?
Solution 1:
Just follow the Elixir docs to add an element to a list ( and keep performance in mind =) ):
iex> list = [1, 2, 3]
iex> [0 | list] # fast
[0, 1, 2, 3]
iex> list ++ [4] # slow
[1, 2, 3, 4]
https://hexdocs.pm/elixir/List.html
Solution 2:
The ++ operator is for concatenating two lists, then maybe what you want to do in order to add a new element is to put it within a list. Then, I think you should add the 3 into another list:
iex(2)> l = [3,5,7,7,8] ++ [3]
[3, 5, 7, 7, 8, 3]