【问题标题】:Read user input and assign string matching result to parameter读取用户输入并将字符串匹配结果分配给参数
【发布时间】:2020-10-08 07:33:50
【问题描述】:

我需要编写一个读取用户输入的谓词。如果输入为“yes”(理想情况下为“yes”或“y”),则必须将 yes 分配给参数,如果输入不同,则必须分配 no。

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

输出是:

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

A = false.

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

A = false.

我做错了什么?

【问题讨论】:

  • 对我有用,如果您更改输入的类型,即检查 Input = yes 是否不带引号。
  • 这能回答你的问题吗? How to Write User Input to a List Prolog
  • 感谢@GuyCoder。这是一个很好的答案,它接近我所需要的,但它没有完全回答这个问题,因为它没有解释如何根据字符串匹配操作的结果有条件地为参数赋值(TA_intern 答案中的 memberchk)。

标签: prolog


【解决方案1】:

您做错的是将使用read 读取的原子与字符串进行比较。相反,将其与原子进行比较(单引号或无引号):

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

您可以使用其他东西来代替read。也许您不想在回答后输入“.”。如果您在按下 Enter 之前一直阅读:

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
    ).

这将正确识别“是”、“是”、“y”、“Y”等。

?- 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.

【讨论】:

  • 最后一个读输入建议在read/1之前使用read_string/5
  • 但是这可能是一个重复的问题,因为我已经建议使用 read_string/5 很长一段时间了。
猜你喜欢
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 2017-08-15
  • 2011-07-13
  • 1970-01-01
  • 2013-04-23
  • 1970-01-01
  • 2017-08-15
相关资源
最近更新 更多