Pattern Matching Erlang?

2019-08-26 03:04发布

问题:

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)

Code here:

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:

In this kind of context, you can use the shell to test why you get an error (or go to the documentation).

if you try:

1> io:get_line("test ").
test yes
"yes\n"
2>

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.

but I prefer case statements

    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.