Erlang pattern matching?

I have this code with an if statement that tries to force the user to enter yes or no if the user enters anything other than yes, the request is rejected. 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)

The code is 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.
0
source share
1 answer

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

if you try:

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

you can see that the io: get_line / 1 does not return a tuple {ok,Input}, a single string, complete with a carriage return: "yes\n". This is reported in the error message.

Thus, your code can be changed 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.

case

    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.
+4

Source: https://habr.com/ru/post/1530827/


All Articles