I have defined a module named operation
and every time I insert or delete the value it will update the final list.
defmodule Operation do
def add(item) do
end
def delete(item) do
end
end
Now the problem here is that if I define an empty array in add
method then how will the values get incremented.
def add(item) do
list = []
list = list ++ item
end
Every time when I try to add an item it will trigger the empty list and will not update the list. What can I do in order to resolve this issue?
Hi @owaisqayum. Welcome to the forum.
You need to pass the list
to your add
function together with the item
you want added.
def add(list, item) do
list ++ item
end
Then, you use it like this:
iex> a_list = [1,2,3]
[1, 2, 3]
iex> Operation.add(a_list, 4)
[1, 2, 3, 4]
1 Like
Variables and bindings are immutable in Elixir. You need to use some way to have mutability. Possible solution is for example using process for storing the list. You can also use other approaches but in general you will need some way to store state between calls.
Where will I define this list
and if it’s empty initially then its kind of same as data is immutable in elixir.
Exactly thats the main issue i am facing. What can i use to save the list.
You are right. The list returned by my example will be a new one. Maybe I should have written like this:
iex> a_list = [1,2,3]
[1, 2, 3]
iex> a_different_list = Operation.add(a_list, 4)
[1, 2, 3, 4]
iex> a_list
[1, 2, 3]
a_list
wasn’t changed by the function call.
For example, imagine this code:
iex> [] |> Operation.add(1) |> Operation.add(2) |> Operation.add(3)
[1, 2, 3]
You start with an empty list and by repeatedly calling the function each time feeding the output of the previous call as input to the new call you build out a list.
1 Like