Trasplazio Garzuglio
Trasplazio Garzuglio

Reputation: 3585

Read user input and assign string matching result to parameter

I need to write a predicate that reads user input. If the input is "yes" (ideally "yes or "y") it must assign yes to the parameter, if it is any different it must assign no.

askContinue(Answer) :-
    write("Would you like to continue ?  "), read(Input), nl,
    (Input = "yes" -> Answer = true ; Answer = false).

The output is:

?- askContinue(A).
Would you like to continue ? yes.

A = false.

?- askContinue(A).
Would you like to continue ? no.

A = false.

What am I doing wrong ?

Upvotes: 3

Views: 341

Answers (1)

TA_intern
TA_intern

Reputation: 2436

What you are doing wrong is that you are comparing the atom that you read using read with a string. Instead, compare it to an atom (single quotes or no quotes):

askContinue(Answer) :-
    write("Would you like to continue ?  "), read(Input), nl,
    (Input = yes -> Answer = true ; Answer = false).

You can use something else instead of read. Maybe you don't want to have to type in "." after your answer. If you read until Enter is pressed:

ask(Prompt, Answer) :-
    prompt1(Prompt),
    read_string(current_input, "\n", " \t", _Sep, Response),
    response_answer(Response, Answer).

response_answer(Response, Answer) :-
    string_lower(Response, R),
    (   memberchk(R, ["y", "yes"])
    ->  Answer = yes
    ;   Answer = no
    ).

This will correctly recognize "Yes", "yes", "y", "Y" and so on.

?- ask("Would you like to continue? ", Answer).
Would you like to continue? Y
Answer = yes.

?- ask("Would you like to continue? ", Answer).
Would you like to continue? Yeah
Answer = no.

Upvotes: 5

Related Questions