0
votes

I am trying to start a simple process that will loop and receive addition or subtraction commands to calculate them. However when I register my process I try to print it with a whereis() to see if it is up and running and it returns undefined. Any idea what is going wrong?

-module(math).
-export([start/0, math/0]).

start() -> register(myprocess, spawn(math, math(),  [])).
    
math() -> 
    io:format("~p~n", [whereis(myprocess)]),
    receive
        {add, X, Y} ->
            io:format("~p + ~p = ~p~n", [X,Y,X+Y]),
            math();
        {sub, X, Y} ->
            io:format("~p - ~p = ~p~n", [X,Y,X-Y]),
            math()
    end.

Here is my input in the erl shell as well:

Eshell V12.0  (abort with ^G)
1> c(math).      
{ok,math}
2> math:start().
undefined
1
it's a long time since I wrote any Erlang, but it looks to me like you're calling math() before the register because it's being passed as a parameter to spawn and that in turn to register. I suspect the brackets after math in the spawn call are not supposed to be there. - Alnitak
Exactly what @Alnitak said: Replace start() -> register(myprocess, spawn(math, math(), [])). by start() -> register(myprocess, spawn(math, math, [])). and it should work fine. - Brujo Benavides
erlang.org/doc/reference_manual/… 'or undefined if the name is not registered' - Joel

1 Answers

3
votes

Remove the parens on the math() parameter passed to spawn.

The second parameter to spawn is supposed to be the atom for the name of the process, but you're actually invoking the function and passing the result to spawn (all of which has to happen before register itself is called).