![](/img/trans.png)
[英]How to wait for the input from user and proceed with further code in erlang concurrent programming?
[英]Erlang concurrent programming
編寫一個名為 Erlang function 的計算器,它不需要 arguments。 function 在進程中運行時,應等待接收消息。 如果消息是四項元組的形式: { Pid, Operand, X, Y }
,請執行以下操作:
然后,重新運行 function。
如果消息是元組的形式,有兩個項目:{ Pid, terminate },然后向完成的 Pid 發送消息。 不要重新運行 function。
如果消息是任何其他形式,忽略它並重新運行 function。
我的代碼:
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.
有人可以幫我解決這個問題嗎?
您的代碼無法編譯,您應該先查看基本的 erlang 語法。
我給你一些線索:
您不應該使用if
語句來解決您的問題,而是使用模式匹配,例如
receive
{From,add,X,Y} ->
From ! X+Y,
calculate();
{From,sub,X,Y} ->
...
通常,為此目的,使用add
之類的原子而不是"add"
類的字符串
你應該有一個 function 在單獨的過程中啟動 function calculate/0
:
start() ->
spawn(fun() -> calculate() end).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.