What does “&1” mean in elixir function?

泄露秘密 提交于 2021-01-02 22:59:16

问题


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 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.



来源:https://stackoverflow.com/questions/55067455/what-does-1-mean-in-elixir-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!