问题
Given this function, what does &1
refer to?
Enum.map [1, 2, 3, 4], &(&1 * 2)
回答1:
&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
回答2:
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
becausex
is the first argumenty == &2
becausey
is the second argumentz == &3
becausez
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.
来源:https://stackoverflow.com/questions/55067455/what-does-1-mean-in-elixir-function