prolog: X > Y breaks the cycle

Viewed 42

I'm trying to implement something like a while loop in prolog but when the X > Y is false it breaks and does nothing else.

Example:

loop(X, Y):-
    X > Y, 
    Y1 is Y +1,
    loop(X,Y1),
    write(Y), tab(1).

Is there any way of making it work wihout changing the loop and the write?

2 Answers

Simple:

loop(X, Y):- X < Y.
loop(X, Y):-
    X >= Y, 
    Y1 is Y +1,
    loop(X,Y1),
    write(Y), tab(1).

Here's my run:

?- loop(10,1).
10 9 8 7 6 5 4 3 2 1 

You can add a base case to prevent it from breaking.

loop(Y,Y).
loop(X, Y):-
    X > Y, 
    Y1 is Y +1,
    loop(X,Y1),
    write(Y), tab(1).

output :

9 8 7 6 5 4 3 2 1 
true 

if you want to make it continue to 10 then you will need to adjust it like that.

loop(X,Y):- succ(X,Y). % stop at Y #= X + 1
loop(X, Y):-
    X >= Y, % until X = Y
    Y1 is Y +1,
    loop(X,Y1),
    write(Y), tab(1).
Related