在Erlang中,如何解释'fun Erlang:'+'/2中的'+'运算符

kxe2p93d  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(185)

I'm new to Erlang but have some experience with Elixir . 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. The first item in the tuple is an atom named simple , the next function and the last an integer :

{atom, function, integer}

I don't understand what the function fun erlang:'+'/2 is doing in this context. The /2 means it should take 2 params. Is the '+' just an addition operator? If so, is this a simple sum function and I am overthinking it? 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 @."
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.
Is it equivalent of doing &:erlang.+/2 in elixir? Doc Reference
Any context would really help.

vybvopom

vybvopom1#

您完全正确--这个函数只是加法运算符,它用单引号括起来,因为它不是以小写字母开头。fun erlang:'+'/2相当于Elixir的&:erlang.+/2
可以使用函数语法而不是运算符语法来调用它:

> erlang:'+'(1,2).
3

你可以把它当作一个高阶函数:

> lists:foldl(fun erlang:'+'/2, 0, [1, 2, 3]).
6

(Of当然,您通常会使用lists:sum/1,而不是后一个示例。)

px9o7tmv

px9o7tmv2#

根据Erlang文档,这种特殊用法是指定Fun表达式的一种形式,它是fun Module:Name/Arity

相关问题