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.
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. fun erlang:'+'/2
is equivalent to Elixir's &:erlang.+/2
.
You can call it using function syntax instead of operator syntax:
> erlang:'+'(1,2).
3
And you can use it as a higher-order 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.)