In the following code I use agent to “save state” of a list and then I update the list.
(I know elixir does not have objects but naming my functions as such helps me reason about the code )
defmodule M do
def create_object() do
{:ok, pid} = Agent.start_link(fn -> [1, 2, 3] end)
pid
end
def update_object(pid, new_data) do
Agent.update(pid, fn (state) -> state ++ new_data end)
pid
end
def get_object(pid) do
IO.inspect Agent.get(pid, &(&1))
end
end
M.create_object() |> M.update_object([4, 5]) |> M.get_object()
The following code has the same result but does not use agent. What can the code that does use agent do that the following code can not? Asking this question is my attempt to see what I am not understanding.
defmodule M do
def create_object() do
obj = [1, 2, 3]
obj
end
def update_object(obj, new_data) do
obj = obj ++ new_data
obj
end
def get_object(obj) do
IO.inspect obj
obj
end
end
M.create_object() |> M.update_object([4, 5]) |> M.get_object()






















