模式匹配Erlang?

时间:2014-05-10 00:24:26

标签: compiler-errors erlang

我有一个带有if语句的代码,该语句试图让用户输入yes或no,如果用户输入了除请求被拒绝以外的任何内容。这是我得到的错误:

** 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 个答案:

答案 0 :(得分:4)

在这种情况下,您可以使用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.