News for hackers. Stuff that matters.
Re:My favorite Erlang program (2013) by h0l0cube on Thursday September 07, 2023 @12:01AM (#37414613)
To explain further, the `receive` keyword is a bit like a switch statement (but actually a pattern matcher) for incoming messages.

Here they made a new server that takes an return process (From) and a number (N). The exclamation point sends the result back to the return process.

    factorial_server() ->
        receive
           {From, N} ->
               From ! factorial(N),
               factorial_server()
        end.

    factorial(0) -> 1;
    factorial(N) -> N * factorial(N-1).
This code then spawns the server, sends a message to that server to become a factorial server, then tells that server to send it back a message with the factorial of 50. It then specifies it's own message listener that takes whatever it receives and returns it.

    test() ->
        Pid = spawn(fun universal_server/0),
        Pid ! {become, fun factorial_server/0},
        Pid ! {self(), 50},
        receive
            X -> X
        end.
A couple of the major advantages of Erlang its distributed parallel nature, and also hot code update. Which happens in `Pid ! {become, fun factorial_server/0}` where it overides the receive loop of universal_server with that of the factorial_server. Though I think proper hot code update doesn't work like this
Re:My favorite Erlang program (2013) by coldtea on Thursday September 07, 2023 @06:20AM (#37416890)
And /0 is the local vm?
Re:My favorite Erlang program (2013) by chrisoverzero on Thursday September 07, 2023 @06:34AM (#37417007)
`/0` refers to the arity of the function.
Re:My favorite Erlang program (2013) by codemonkey-zeta on Thursday September 07, 2023 @07:23AM (#37417370)
It's the arity of the function. In Erlang there are no variadic functions, but functions with different arities can have the same name, so universal_server/0 takes no arguments, fib/1 takes 1 argument, fib/2 takes 2 arguments, the second arg may be the accumulator for a recursive Fibonacci, for example, and fib/1 may call fib/2 as an implementation detail.