I'm trying to build a chess game in Prolog, and I started by studying this Stack Overflow post How to access two dimensional array in prolog and how to loop each element in it, because I think the chess game involves data of the board and pieces in a form of two dimensional array. So right now I'm trying to experiment with a simpler array to understand how it works first.
By making the most of the example code provided in the link above, I wrote a print_array(Array)
predicate, along with the code below.
arraysample([[[1],[2],[3]],[[4],[5],[6]],[[7],[8],[9]]]).
array1([[1],[2],[3],[4],[5]]).
print_array(Array):-
print_rows(Array).
print_rows([]):-
write(''),nl. % trying to create a new line before moving on to the next row,
% but at this moment it's not working
print_rows([Row|Rows]):-
print_row(Row),
print_rows(Rows).
print_row([]).
print_row([Cell|Columns]):-
print_cell(Cell),
print_row(Columns).
print_cell(Cell):-
write(Cell),
write(' ').
and when I call the predicate with a hard-coded array like this, it properly prints out the array with the result true
.
?- print_array([[[1],[2],[3]],[[4],[5],[6]],[[7],[8],[9]]]).
[1] [2] [3] [4] [5] [6] [7] [8] [9]
true.
But when I use the array name, it fails.
?- print_array(array1).
false.
And when I used trace
to see what was going on, it only displayed me something like this.
?- trace(print_array(array1)).
% print_array/1: [call,redo,exit,fail]
true.
Why does calling the predicate with an array name fail while it works with a hard-coded array? How can I get it to work with an array name as well?
NOTE: Please provide me with some concrete examples by showing me some code when you answer my question, just like I pasted my code in my question. If you are thinking of posting an abstract comment like "Read the Prolog documentation, period.", which is not an answer for any specific question at all, don't write anything in the first place. Thanks in advance.
trace.
, then enter your queryprint_array(array1).
separately, you'll get detailed query steps. – lurkerarray1([[1],[2],[3],[4],[5]]).
asserts a factarray1
with argument,[[1],[2],[3],[4],[5]]
.array1
is not a variable representing the value[[1],[2],[3],[4],[5]]
. So callingprint_array(array1)
does not subsitute[[1],[2],[3],[4],[5]]
forarray1
in the call.print_array
just sees an atom,array1
which is not a list so it fails immediately. Try,array1(X), print_array(X).
. – lurker