prolog - Prolog 99瓶啤酒

标签 prolog swi-prolog

以下代码和查询不起作用:

bottles(X) :-
    write(X), write(' bottles of beer on the wall,'), nl,
    write(X), write(' bottles of beer,'), nl,
    write('Take one down, and pass it around,'), nl,
    X1 is X - 1,
    write(X1), write(' bottles of beer on the wall.'), nl,
    bottles(X1).
bottles(1) :-
    write('1 bottle of beer on the wall, 1 bottle of beer,'), nl,
    write('Take one down, and pass it around,'), nl,
    write('Now they are alle gone.'), nl.

?- bottles(99).

使用 Windows 上的 SWI-Prolog 8.3.15,我什至不能按 Ctrl-C。

出了什么问题?

最佳答案

它将始终保持递归,因为第一条规则从未规定 X 应该大于 1。因此,您可以通过以下方式修复此问题:

bottles(X) :-
    <b>X > 1</b>,  %% ← check that X is greater than one.
    write(X), write(' bottles of beer on the wall,'), nl,
    write(X), write(' bottles of beer,'), nl,
    write('Take one down, and pass it around,'), nl,
    X1 is X - 1,
    write(X1), write(' bottles of beer on the wall.'), nl,
    bottles(X1).
bottles(1) :-
    write('1 bottle of beer on the wall, 1 bottle of beer,'), nl,
    write('Take one down, and pass it around,'), nl,
    write('Now they are alle gone.'), nl.

关于prolog - Prolog 99瓶啤酒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65401793/

相关文章:

macos - 如何设置 PrologScript

prolog - 如何以更快的方式将文件查阅到 swi-prolog

module - 如何在 swi-prolog 中导入运算符?

Prolog:忽略输出中不需要的变量

prolog - 序言中的“如果”?

prolog - SWI Prolog 查询

prolog - 为什么这个简单的 Prolog 示例会导致堆栈溢出?

list - 删除序言中列表中的共享项目

prolog - 如何正确过滤返回多个重复值的子句?

prolog - 理解clpfd中label/5的实现