Reputation: 121
I wrote this function where I have as a parameter a set of coordinates and I want to create a new list with all the coordinates to the left of them (so basically X-1) but at the end it doesn't ask me if the option given is correct, it just prints yes
.
Here is the code:
all_valid_moves([], L):-
write('------------------------'),
nl,
write(L),
nl,
write('------------------------'),
nl,
!.
all_valid_moves([Head|Tail], All_Valid):-
nth0(0, Head, X),
nth0(1, Head, Y),
NewX is X - 1,
append([[NewX, Y]], All_Valid, New_All_Valid),
write(All_Valid),
nl,
all_valid_moves(Tail, New_All_Valid).
Test case all_valid_moves([[1,1],[2,2],[3,3]], X).
.
Should return [[0,1],[1,2],[2,3]]
.
If anyone can point out the mistake(s) I made, please do so! Thanks alot for your time, Have a good one
Upvotes: 0
Views: 53
Reputation: 74227
Simplify, simplify, simplify. No need for nth0/3
. No need for append/3
. Just this:
all_valid_moves( [] , [] ) .
all_valid_moves( [[X,Y]|As] , [[X1,Y]|Bs] ) :- X1 is X-1, all_valid_moves(As,Bs).
Upvotes: 0
Reputation: 121
Final answer
I added a new variable to the function so I could return it in a new list, this was the final result:
all_valid_moves(Board, [], L, New):-
New = L.
all_valid_moves(Board, [Head|Tail], Previous, All_Valid):-
nth0(0, Head, X),
nth0(1, Head, Y),
NewX is X - 1,
append([[NewX, Y]], All_Valid, New_All_Valid),
all_valid_moves(Board, Tail, New_Prev3, New_All_Valid),
All_Valid = New_All_Valid.
Upvotes: 1