2
votes

Hi I'm learning Erlang and in the process I'm trying to do the exercises from the Erlang execises page. In particular I'm doing the problem where I have to create a function that creates two processes that send M messages to the other and then die. I'm having trouble with it, this my code:

-module(roundtrip).
-export([talk/1]).

talk(M) ->
    init(M).

init(M) ->
    P1 = start(M),
    P2 = start(M),
    P2 ! {P1, a_message}.

myProc(M) ->
    if M =:= 0 ->
        io:format("Bye cruel world!~n")
    end,
    receive
        {From, a_message} ->
            From ! {self(), a_message},
            myProc(M-1);
        _ -> 
            io:format("I don't understand~n"),
            myProc(M)

    end.

start(M) ->
    spawn(?MODULE, myProc, [M]).

I get when I call the talk the following errors:

=ERROR REPORT==== 11-Nov-2013::21:21:00 === Error in process <0.46.0> with exit value: {undef,[{roundtrip,proc,"\n",[]}]}

=ERROR REPORT==== 11-Nov-2013::21:21:00 === Error in process <0.47.0> with exit value: {undef,[{roundtrip,proc,"\n",[]}]}

I'm going around it but I can't figure out what's the problem...

Thanks.

2

2 Answers

3
votes

Since you use spawn/3 you need to export myProc.

Another problem is that your if condition does not cover the other possibility when M =/= 0. I'd do it like this:

-module(roundtrip).

-export([talk/1]).

talk(M) ->
    init(M).

init(M) ->
    P1 = start(M),
    P2 = start(M),
    P2 ! {P1, a_message}.

myProc(M) ->
    case M of
        0 ->
            io:format("Bye cruel world!~n");
        _ ->
            receive
                {From, a_message} ->
                    From ! {self(), a_message},
                    io:format("~p ~p~n", [self(), M]),
                    myProc(M-1);
                _ ->
                    io:format("I don't understand~n"),
                    myProc(M)

            end
    end.

start(M) ->
    spawn(fun() -> myProc(M) end).

Note that I used case instead of if and spawn/1 instead of spawn/3.

3
votes

You need to export myProc/1 function. Or you can use spawn/1:

start(M) ->
   spawn(fun() -> myProc(M) end).