ameerFIJI
ameerFIJI

Reputation: 57

Sending/receiving messages in Erlang (Concurrency)

I am trying to solve the following problem:

Write an Erlang function named respond that takes two parameters, a process ID named Pid and an Erlang item named Item. The function should send a message to Pid; the message should be a tuple with two elements: respond’s process ID and Item. Then, the function should wait to receive a message back. If the message it receives is true, then print “That is correct!” If the message it receives is false, then print “That is incorrect!” If the message it receives is an error, then print “There was an error in the input.” If the message is anything else, then print “Invalid message received.”

I have written the following:

respond(Pid,Item) ->
  Pid ! {Pid,Item};
receive
  true -> io:format(~p~n "That is correct",[]);
  false -> io:format(~p~n "That is incorrect",[]);
  error -> io:format(~p~n "There was an error in the input",[]);
  _ -> io:format(~p~n "Invalid message received",[])
 end.

The error that I am getting when I compile my code is as follows:

1> c(main).
main.erl:15: syntax error before: 'receive'
main.erl:2: function respond/2 undefined
error

What is causing this error? Also is my problem solving approach for this Question correct?

Upvotes: 2

Views: 667

Answers (1)

Brujo Benavides
Brujo Benavides

Reputation: 1958

You're really really close.

The issue is that expressions in Erlang are not delimited by ;. They're delimited by ,.

Try…

respond(Pid,Item) ->
  Pid ! {Pid,Item},
…

Also… a small-ish tip: respond’s process ID is not Pid. To obtain respond’s process ID, you should use self/0.

Upvotes: 5

Related Questions