Prolog 中的 99 瓶啤酒

99 bottles of beer in 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).

使用 SWI-Prolog 8.3.15 Windows 我什至不能按 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.