Erlang并发程序设计

k4emjkb1  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(173)

Write an Erlang function named calculator that takes no arguments. The function, when run in a process, should wait to receive a message. If the message is in the form of a tuple of four items: { Pid, Operand, X, Y } , do this:

  • If Operand is add, send a message to Pid with the result of adding X and Y.
  • If Operand is subtract, send a message to Pid with the result of subtracting Y from X.
  • If Operand is multiply, send a message to Pid with the result of multiplying X and Y.
  • If Operand is divide, send a message to Pid with the result of dividing X by Y.

Then, rerun the function.

  • If the message is in the form of a tuple with two items: { Pid, terminate }, then send a message to Pid of done. Do not rerun the function.
  • If the message is of any other form, ignore it and rerun the function.

My code:

calculate() ->
  receive
    {Pid, Operand, X, Y} 
      if 
         Operand == "add" -> Pid ! X+Y
         Operand == "substract" -> Pid ! Y - X
         Operand == "multiply" -> Pid ! X*Y
         Operand == "divide" -> Pid ! X/Y
    {Pid, terminate} -> Pid ! "done"
    _ -> calculate();
  end.

Can someone help me with this problem?

fafcakar

fafcakar1#

你的代码没有编译,你应该先看看基本的Erlang语法。
我给予你一些线索:
您不应该使用if语句来解决问题,而应该使用模式匹配,如

receive
    {From,add,X,Y} ->
        From ! X+Y,
        calculate();
    {From,sub,X,Y} -> 
    ...

通常,为此,使用add这样的原子,而不是"add"这样的字符串
您应该有一个函数在一个单独的进程中启动函数calculate/0

start() ->
    spawn(fun() -> calculate() end).

相关问题