Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the '&' operator work?

Tags:

elixir

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.

like image 816
cogle Avatar asked Jun 23 '16 04:06

cogle


1 Answers

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)
like image 158
Paweł Obrok Avatar answered Oct 30 '22 21:10

Paweł Obrok