我有一个带有if语句的代码,该语句试图让用户输入yes或no,如果用户输入的不是yes,则请求被拒绝。这是我得到的错误:
** exception error: no match of right hand side value "yes\n"
in function messenger:requestChat/1 (messenger.erl, line 80)
代码在这里:
requestChat(ToName) ->
case whereis(mess_client) of
undefined ->
not_logged_on;
_ -> mess_client ! {request_to, ToName},
request_to = io:get_line("Do you want to chat?"),
{_, Input} = request_to,
if(Input == yes) ->
ok;
true -> {error, does_not_want_to_chat}
end
end.
最佳答案
在这种情况下,您可以使用 shell 程序测试为什么会出错(或转到文档)。
如果你试试:
1> io:get_line("test ").
test yes
"yes\n"
2>
您会看到io:get_line/1不会返回元组
{ok,Input}
,而是返回以回车符结尾的简单字符串"yes\n"
。这就是错误消息中报告的内容。因此,您的代码可以修改为:
requestChat(ToName) ->
case whereis(mess_client) of
undefined ->
not_logged_on;
_ -> mess_client ! {request_to, ToName},
if
io:get_line("Do you want to chat?") == "yes\n" -> ok;
true -> {error, does_not_want_to_chat}
end
end.
但我更喜欢案例陈述
requestChat(ToName) ->
case whereis(mess_client) of
undefined ->
not_logged_on;
_ -> mess_client ! {request_to, ToName},
case io:get_line("Do you want to chat?") of
"yes\n" -> ok;
"Yes\n" -> ok;
_ -> {error, does_not_want_to_chat}
end
end.
关于compiler-errors - 模式匹配Erlang?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23575901/