문제

I am very green with Prolog. I have a 7-by-7 grid and for each cell I store the X, the Y, and two other things, like this: cell(1, 1, 0, 0).

I want to traverse the grid and reset the values of the cells if they are not given, so I created these functions:

given(X, Y):- (cell(X, Y, start, _) ; cell(X, Y, end, _)).
reset_cell(X, Y):- not(given(X, Y)), cell(X, Y, 0, 0).
reset_grid(8, _):- write('finished resetting').
reset_grid(X, 8):- X1 is X + 1, reset_cell(X1, 1), reset_grid(X1, 1).
reset_grid(X, Y):- reset_cell(X, Y), Y1 is Y + 1, reset_grid(X, Y1).

But this results in an endless loop because in the last line apparently the parameter passed to the reset_grid function remains at value 1. What am I doing wrong?

Edit: I forgot to mention that I call the function like this: ?- reset_grid(1, 1).

Edit 2: (new version as per Sergey's instructions):

reset_grid(X, _):- X > 7, write('finished resetting').
reset_grid(X, Y):- Y > 7, X1 is X + 1, reset_cell(X1, 1), reset_grid(X1, 1).
reset_grid(X, Y):- X < 8, Y < 8, reset_cell(X, Y), Y1 is Y + 1, reset_grid(X, Y1).
도움이 되었습니까?

해결책

The problem is that when you have a call reset_grid(1, 8), your reset_grid(X, 8) clause fires, but after that reset_grid(X, Y) also fires.

To fix this you can add cut '!' to the reset_grid(X, 8) clause or add Y < 8 to the reset_grid(X, Y), or do both (to get a so-called 'green cut').

The similar problem with call reset_grid(8, 8): reset_grid(8, _) will match, but after that reset_grid(X, Y) will match. Fix in the similar manner.

UPDATE.

Try to change you reset cell definition to just logging X and Y. With this code:

reset_cell(X, Y) :- write([X, Y]), nl.
reset_grid(X, _):- X > 7, write('finished resetting').
reset_grid(X, Y):- Y > 7, X1 is X + 1, reset_cell(X1, 1), reset_grid(X1, 1).
reset_grid(X, Y):- X < 8, Y < 8, reset_cell(X, Y), Y1 is Y + 1, reset_grid(X, Y1).

I get this result:

?- reset_grid(1, 1).
[1,1]
[1,2]
[1,3]
[1,4]
[1,5]
[1,6]
[1,7]
[2,1]
[2,1]
[2,2]
[2,3]
[2,4]
[2,5]
[2,6]
[2,7]
[3,1]
[3,1]
[3,2]
[3,3]
[3,4]
[3,5]
[3,6]
[3,7]
[4,1]
[4,1]
[4,2]
[4,3]
[4,4]
[4,5]
[4,6]
[4,7]
[5,1]
[5,1]
[5,2]
[5,3]
[5,4]
[5,5]
[5,6]
[5,7]
[6,1]
[6,1]
[6,2]
[6,3]
[6,4]
[6,5]
[6,6]
[6,7]
[7,1]
[7,1]
[7,2]
[7,3]
[7,4]
[7,5]
[7,6]
[7,7]
[8,1]
finished resetting
true ;
false.

So the loop works and terminates. Maybe the problem in the last call reset_cell(8, 1)? Otherwise it's with the reset_cell predicate itself or the predicates called from reset_cell. Show the rest of your code so it can be tested.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top