模式匹配Erlang? [英] Pattern Matching Erlang?
本文介绍了模式匹配Erlang?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个if语句的代码,试图让用户输入yes或no,如果用户输入的东西不是yes的请求被拒绝。这是我得到的错误:
I have this code with a if statement which is trying to get the user to input yes or no if the user inputs anything other than yes the request is denied. This is the error I get:
** 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.
推荐答案
在这种情况下,
如果您尝试:
1> io:get_line("test ").
test yes
"yes\n"
2>
您可以看到io:get_line / 1不返回元组 { ok,Input}
但是一个简单的字符串由aa回车符结束:yes\\\
。
you can see that io:get_line/1 does not return a tuple {ok,Input}
but a simple string terminated by a a carriage return: "yes\n"
. That is what it is reported in the error message.
因此,您的代码可以修改为:
So your code can be modified to:
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.
这篇关于模式匹配Erlang?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文