I want to implement a couple of operations on a list (not using ++ or other existing operations). For example:
defmodule ListMod do
use Agent
def start_link(_opts) do
Agent.start_link(fn -> [] end)
end
def put_list(agent, value) do
Agent.update(agent, fn list -> [value | list] end)
end
def no_items(agent) do
Agent.get(agent, fn list -> count(list) end)
end
end
How can I spawn some different processes to do the work for the functions:
fn -> [] end
fn list -> [value | list] end
fn list -> count(list) end
But why you would want that? Why even spawn a process for a simple list? If you want to implement list on your own, without built in list then you can treat list as a tuples, so {}
is an empty list and {val, tail}
is the element of the list, so now we can have:
defmodule TupleList do
def hd({val, _tail}), do: val
def tl({_val, tail}), do: tail
def length({}), do: 0
def length({_, tail}), do: length(tail) + 1
def fold(fun, acc, {}), do: acc
def fold(fun, acc, {val, tail}), do: fold(fun, fun.(acc, val), tail)
def append(val, list), do: {val, list}
end
And this is enough to implement all other functions that can operate on lists.
1 Like
Well as an excersice it might make sense. So you could as you suggested spawn processes by calling start link several times.
Then you can play with your agents returned by start link…
Can you show in code how can I spawn a process for one of the functions and send the result back?