这个匿名函数的语法是怎么回事? [英] what's up with this anonymous function syntax?

查看:80
本文介绍了这个匿名函数的语法是怎么回事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的药剂之旅开始。在书中阅读:

Just starting on my Elixir journey. Reading this in a book:


&运算符将后面的表达式转换为函数。

"The & operator converts the expression that follows into a function."

好,我想我...

iex(70)> f = &(&1 * &2)
#Function<12.80484245 in :erl_eval.expr/5>
iex(72)> f.(2,3)
6

好的,&号是匿名函数的简写这是争论。但是,为什么下一个呼叫不起作用?!

ok, ampersand is a shorthand for anonymous function and it's arguments. But then, why this next call doesn't work?!

iex(73)> &(&1 * &2).() 
#Function<12.80484245 in :erl_eval.expr/5>

...而且我似乎永远可以继续这样做:

...and I can keep doing this seemingly forever:

iex(76)> &(&1 * &2).().().()
#Function<12.80484245 in :erl_eval.expr/5>

这里发生了什么?

推荐答案

如果用括号将匿名函数包装起来,它将起作用:

If you wrap the anonymous function with parentheses, it will work:

iex(1)> (&(&1 * &2)).()
** (BadArityError) &:erlang.*/2 with arity 2 called with no arguments

预计会出现错误,因为我们称零参数为2 arity。如果我们给它传递两个数字,我们应该看到它们相乘:

The Error is expected, as we're calling a 2 arity fun with zero arguments. If we pass it two numbers, we should get see them get multiplied together:

iex(2)> (&(&1 * &2)).(2,3)
6

这篇关于这个匿名函数的语法是怎么回事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆