作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
是否可以在不调用谓词且不创建新谓词的情况下返回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.
Print this message again? (yes/no)
yes.
Welcome.
You selected yes.
Print this message again? (yes/no)
no.
程序结束。
最佳答案
重复repeat/0
是simply 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
).
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
的作业,因此处理
yes
,
no
和错误输入的部分显然没有指定,并且坦率地说,这并没有真正的意义。我保留了原始语义,并合并了
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/
我是一名优秀的程序员,十分优秀!