14

Given this function, what does &1 refer to?

Enum.map [1, 2, 3, 4], &(&1 * 2)
Mike
  • 1,884
  • 2
  • 24
  • 42
  • Possible duplicate of [Why are there two kinds of functions in Elixir?](https://stackoverflow.com/questions/18011784/why-are-there-two-kinds-of-functions-in-elixir) – Darragh Enright Mar 10 '19 at 22:47
  • Possible duplicate of [How does the '&' operator work?](https://stackoverflow.com/questions/37982351/how-does-the-operator-work) – Paweł Obrok Mar 12 '19 at 16:43

2 Answers2

23

&1 refers to the first argument the callback function would receive. The ampersand by itself (&) is a shorthand for a captured function. This is how you could expand that function.

Enum.map([1, 2, 3, 4], fn x -> x * 2 end)

fn -> is equal to &(...

x -> x is equal to ...(&1

A quick reference can be found here

Mike
  • 1,884
  • 2
  • 24
  • 42
13

The &(1 + &1) syntax in elixir is simply another way to write an anonymous function.

So given the above:

fn(x) -> 1 + x end

Is identical to

&(1 + &1)

It's just another way of writing anonymous functions, typically used when you are doing a small unit of operation or simply calling another function.

Each &n when using that syntax, refers to the position of the arguments called in that function.

So:

fn(x, y, z) -> x + y + z end

Would mean that if you were to use the shorthand & anonymous function syntax:

  • x == &1 because x is the first argument
  • y == &2 because y is the second argument
  • z == &3 because z is the third argument

Another way of representing these arguments is by using the anonymous function + arity syntax which pretty much acts as a delegator.

So for example, lets say that you wanted to map over a list of values and apply a function each value. Using the basic anonymous function syntax, it would look like:

Enum.map([1, 2, 3], fn(x) -> add_one(x) end)

Using the & with argument captures (&1)

Enum.map([1, 2, 3], &(add_one(&1))

Using the & with arity matching:

Enum.map([1, 2, 3], &add_one/1)

Which simply says, that this anonymous function will take only 1 argument and that argument should be applied to the function called add_one which is also a 1 arity function.

So those three examples above are exactly the same and will all result in add_one being called on each argument.

Harrison Lucas
  • 2,829
  • 19
  • 25