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?
1条答案
按热度按时间fafcakar1#
你的代码没有编译,你应该先看看基本的Erlang语法。
我给予你一些线索:
您不应该使用
if
语句来解决问题,而应该使用模式匹配,如通常,为此,使用
add
这样的原子,而不是"add"
这样的字符串您应该有一个函数在一个单独的进程中启动函数
calculate/0
: