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?
insert() Method. Use the insert() method when you want to add data to the beginning or middle of a list. Take note that the index to add the new element is the first parameter of the method.
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
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]
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