【问题标题】:Pattern Matching Erlang?模式匹配 Erlang?
【发布时间】:2014-06-27 20:38:23
【问题描述】:

我有这个带有 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.

【问题讨论】:

标签: compiler-errors erlang


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-12-08
    • 2011-08-14
    • 2011-06-17
    • 2013-08-15
    • 2011-09-29
    • 2010-12-13
    • 2014-07-26
    • 2015-01-12
    • 2015-02-09
    相关资源
    最近更新 更多