concurrency - 在 Erlang 中发送/接收消息(并发)

标签 concurrency functional-programming erlang

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

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.”

我写了以下内容:

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

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

最佳答案

你们真的非常接近。

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

尝试...

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

还有……一个小提示:响应的进程 ID 不是 Pid。要获取响应的进程 ID,您应该使用 self/0 .

关于concurrency - 在 Erlang 中发送/接收消息(并发),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66383303/

相关文章:

sockets - Erlang 变量模式匹配

.net - 等同于Akka,但适用于.NET(并发框架)

ios - CoreData 并发 - 我需要一个单独的 NSOperationQueue 吗?

scala - 元组函数输出

generics - Kotlin 中的通用 lambda 或函数值类型

windows - 如何使用 erlang.el 设置 Erlang + Emacs?

concurrency - Rust vs Go 并发网络服务器,为什么 Rust 在这里很慢?

sql - Oracle SQL - SELECT 查询锁定索引并阻止 DML session

javascript - 有没有办法使用 ramda 将参数传递给 JavaScript 中的谓词?

list - Erlang 中的映射函数