99 bottles of beer in Prolog

Viewed 69

The following code and query doesn't work:

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

With SWI-Prolog 8.3.15 on Windows I can even not press Ctrl-C.

Whats going wrong?

1 Answers

It will always keep recursing since the first rule never says that X should be greater than one. You thus fix this with:

bottles(X) :-
    X > 1,  %% ← 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.
Related