I am having trouble understand the '&' operator in the following context.
@doc "Marks a task as executed"
def put_task(task, project) do
item = {task, project}
Agent.update(__MODULE__, &MapSet.put(&1, item))
end
It seems that in this case the '&1' is referring to the map object itself, but I am curious as to how this works. Is it passing itself in as an argument I looked into this in the docs but couldn't find out if this was exactly what was going on. I would be grateful if somebody could help me understand what is exactly going on and what &1 refers to and if it refers to the MapSet how is this possible.
The &1
is the first argument of the function. The whole &
notation is basically an alternative way to express anonymous functions - there's nothing specific to Enum
or Agent
about it. Let's take this example:
fn (x, y, z) -> (x + z) * y end
This is an anonymous function that takes 3 arguments, adds the first and third one and multiplies the result by the second one. With the &
notation:
&((&1 + &3) * &2)
Think of the &1
, &2
and &3
as placeholders in an expression where the arguments will go. So when you do
Agent.update(__MODULE__, &MapSet.put(&1, item))
You're calling Agent.update
with a one-argument function that calls MapSet.put
with that argument and item - whatever that is. It's equivalent to:
Agent.update(__MODULE__, fn x -> MapSet.put(x, item) end)
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