[英]In erlang, how do I interpret the `+` operator in `fun erlang:'+'/2`
I'm new to Erlang
but have some experience with Elixir
.我是Elixir
的新手,但对Erlang
有一些经验。 As I've been trying to learn Erlang while experimenting with the RabbitMQ implementation of RAFT, ra , I've come across a line in erlang Machine = {simple, fun erlang:'+'/2, 0},
As I've been trying to learn Erlang while experimenting with the RabbitMQ implementation of RAFT, ra , I've come across a line in erlang Machine = {simple, fun erlang:'+'/2, 0},
Machine = {simple, fun erlang:'+'/2, 0},
So, in {simple, fun erlang:'+'/2, 0},
, this looks like it is creating a tuple.所以,在{simple, fun erlang:'+'/2, 0},
,这看起来像是在创建一个元组。 The first item in the tuple is an atom
named simple
, the next function
and the last an integer
:元组中的第一项是一个名为simple
的atom
,接下来function
和最后一个integer
:
{atom, function, integer}
I don't understand what the function fun erlang:'+'/2
is doing in this context.我不明白 function fun erlang:'+'/2
在这种情况下做了什么。 The /2
means it should take 2 params. /2
表示它应该需要 2 个参数。 Is the '+'
just an addition operator? '+'
只是一个加法运算符吗? If so, is this a simple sum
function and I am overthinking it?如果是这样,这是一个简单的sum
function 我想多了? The erlang docs say "An atom is to be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @." erlang 文档说“如果原子不是以小写字母开头或包含除字母数字字符、下划线 (_) 或 @ 之外的其他字符,则原子将用单引号 (') 括起来。”
In the given context that I'm seeing this code, it states State machine that implements the logic
, which is leading me to understand this state machine as being named with the atom simple
, performs addition, and saves the result in the last item of the tuple.在我看到此代码的给定上下文中,它说明State machine that implements the logic
,这使我理解这台 state 机器以原子simple
命名,执行加法,并将结果保存在最后一项元组。
Is it equivalent of doing &:erlang.+/2
in elixir?是否相当于在 elixir 中执行&:erlang.+/2
? Doc Reference 文档参考
Any context would really help.任何上下文都会有帮助。
You got it exactly right - this function is just the addition operator, and it is enclosed in single quotes because it doesn't start with a lowercase letter.你完全正确 - 这个 function 只是加法运算符,它用单引号括起来,因为它不是以小写字母开头。 fun erlang:'+'/2
is equivalent to Elixir's &:erlang.+/2
. fun erlang:'+'/2
相当于 Elixir 的&:erlang.+/2
。
You can call it using function syntax instead of operator syntax:您可以使用 function 语法而不是运算符语法来调用它:
> erlang:'+'(1,2).
3
And you can use it as a higher-order function:您可以将其用作高阶 function:
> lists:foldl(fun erlang:'+'/2, 0, [1, 2, 3]).
6
(Of course, you'd usually use lists:sum/1
instead of the latter example.) (当然,您通常会使用lists:sum/1
而不是后一个示例。)
As per the Erlang documentation(s), this particular usage is one of the forms for specifying Fun expression , and this one is fun Module:Name/Arity
.根据 Erlang 文档,此特定用法是 forms 之一,用于指定Fun expression ,而这个是fun Module:Name/Arity
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.