gpt4 book ai didi

prolog - 如何在Prolog中返回 “repeat”?

转载 作者:行者123 更新时间:2023-12-04 17:18:17 26 4
gpt4 key购买 nike

是否可以在不调用谓词且不创建新谓词的情况下返回Prolog中的repeat
我有以下代码

test :- nl,
write('Welcome.'),nl,
repeat, write('Print this message again? (yes/no)'),nl,
read(Ans),nl,
(
Ans == yes -> write('You selected yes.'), nl
;
write('You selected no.')
).
我得到的当前输出是
Welcome.
Print this message again? (yes/no)
yes.
You selected yes.
true.
程序结束。
我想要的输出是
Welcome.
Print this message again? (yes/no)
yes.
You selected yes.
Print this message again? (yes/no)
no.
程序结束。
我想避免的简单输出方式(我不需要此输出。我不希望它多次显示Welcome):
Welcome.
Print this message again? (yes/no)
yes.

Welcome.
You selected yes.
Print this message again? (yes/no)
no.
程序结束。

最佳答案

重复
repeat/0simply defined as:

repeat.
repeat :- repeat.

或者,等效地:
repeat :- true ; repeat.

为了进行重复,您需要通过失败(显式地使用 repeat或通过另一个失败的谓词)来回溯到 fail调用(请参见上面链接中的示例)。
...
repeat,
...,
fail.

一旦您想退出重复模式,就可以(并且应该)剪切决策树 !,以便没有悬挂的 repeat选择点。
如果您不这样做,则解释器以后仍然可以回溯到 repeat

注意: !/0的规则可以是 found here

例子

对于您的示例而言,这意味着(顺便说一句,我使用 writeln):
test :- 
nl,
writeln('Welcome.'),
repeat,
writeln('Print this message again? (yes/no)'),
read(Ans),nl,
(Ans == yes ->
writeln('You selected yes.'),
fail % backtrack to repeat
; writeln('You selected no.'),
! % cut, we won't backtrack to repeat anymore
).

其他备注

请注意,OP使用了原子,而字符串已足够。
实际上,原子(单引号)是经过哈希处理的,并且在进行符号推理时更受欢迎,而字符串(双引号)则不会被插入并且更适合显示消息。

本着同样的精神,在阅读时,我宁愿使用 read_string(end_of_line,_,S),它会读取到行尾并返回一个字符串。使用 read/1,我不得不用Ctrl + D关闭输入流,这很烦人。

另外,我们可以完全摆脱 ->:
test :- 
nl,
writeln("Welcome."),
repeat,
writeln("Print this message again? (yes/no)"),
read_string(end_of_line,_,Ans),
nl,
write("You selected "),
write(Ans),
writeln("."),
Ans == "no", % Otherwise, repeat
!.

看到其他人如何争辩更多案例,删除 ->可能会引起争议。这是基本原理:由于最初的问题似乎是有关 repeat的作业,因此处理 yesno和错误输入的部分显然没有指定,并且坦率地说,这并没有真正的意义。我保留了原始语义,并合并了 yes和输入错误的情况:毕竟,当用户说 yes时会发生什么?我们重复一遍,就像用户键入意外的输入时一样。我们不使用 repeat的唯一情况是当 Ans == no时。

现在,如果我们要更改原始代码的行为以便显式检查所有可能的输入,请尝试以下操作:
test :- 
nl,
writeln("Welcome."),
repeat,
writeln("Print this message again? (yes/no)"),
read_string(end_of_line,_,Ans),
nl,
(memberchk(Ans,["yes","no"]) ->
write("You selected "),
write(Ans),
writeln("."),
Ans == "no",
!
; writeln("Bad input" : Ans),
fail).

关于prolog - 如何在Prolog中返回 “repeat”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29857372/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com