【问题标题】:Sending/receiving messages in Erlang (Concurrency)在 Erlang 中发送/接收消息(并发)
【发布时间】:2021-05-28 16:27:33
【问题描述】:

我正在尝试解决以下问题:

编写一个名为response 的Erlang 函数,它接受两个参数,一个名为Pid 的进程ID 和一个名为Item 的Erlang 项。该函数应该向 Pid 发送消息;消息应该是一个包含两个元素的元组:响应的进程 ID 和项目。然后,该函数应该等待接收回消息。如果它收到的消息是真的,那么打印“那是正确的!”如果它收到的消息是错误的,则打印“那是不正确的!”如果它收到的消息是错误的,则打印“输入中有错误”。如果消息是其他内容,则打印“收到无效消息”。

我写了以下内容:

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.

我在编译代码时遇到的错误如下:

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

是什么导致了这个错误?我对这个问题的问题解决方法也正确吗?

【问题讨论】:

    标签: concurrency functional-programming erlang


    【解决方案1】:

    你真的很亲近。

    问题在于 Erlang 中的表达式不是由 ; 分隔的。它们由, 分隔。

    试试……

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

    还有……一个小提示:respond 的进程 ID 不是 Pid。要获得respond的进程ID,你应该使用self/0。

    【讨论】:

      猜你喜欢
      • 2016-10-04
      • 2016-03-19
      • 2019-07-23
      • 2020-10-08
      • 2014-05-28
      • 2014-06-07
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多