Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Elixir 中的匿名函数 #25

Closed
WyattJia opened this issue Jun 11, 2017 · 0 comments
Closed

Elixir 中的匿名函数 #25

WyattJia opened this issue Jun 11, 2017 · 0 comments
Labels

Comments

@WyattJia
Copy link
Owner

就像名字中说明的那样,匿名函数没有名字,它们经常被用来传递给其他函数。
要定义匿名函数,我们需要 fnend 关键字,在这两者之间,我们可以定义任意数量的参数和函数体,它们用 -> 分隔开。

我们来看一个简单的例子:

$ iex
iex> sum = fn (a, b) -> a + b end
iex> sum.(2, 3)
5

& 操作符

因为在 Elixir 中使用匿名函数非常常见,所以有一个快捷方式来做这件事:

$ iex
iex> sum = &(&1 + &2)
iex> sum.(2, 3)
5

在这种简写的模式下,函数的参数可以通过 &1&2&3 等来获取。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant