prologprolog-toplevel

How to change the order in which variables are printed in prolog?


This is a homework problem, but I just need a simple question answered. I am supposed to print all the possible ways a knight can jump on a chess board from it's position. I am getting the correct numbers but I don't seem to get the correct output that I want. For example:

 ?- knight(8,1,R,C)

is supposed to print out the output as:

C = 3
R = 7;
C = 2
R = 6;

But I get the exact opposite as in:

R = 7,
C = 3;
R = 6,
C = 2.

here is my code:

knight(C, R, C2, R2):-
      C2 is C - 1,R2 is R + 2,
      withinBoard(C2,R2)
   ;  C2 is C + 1,R2 is R + 2,
      withinBoard(C2,R2)
   ;  C2 is C + 2, R2 is R + 1,
      withinBoard(C2,R2)
   ;  C2 is C + 2, R2 is R - 1,
      withinBoard(C2,R2)
   ;  C2 is C + 1, R2 is R - 2,
      withinBoard(C2,R2)
   ;  C2 is C - 1, R2 is R - 2,
      withinBoard(C2,R2)
   ;  C2 is C - 2, R2 is R - 1,
      withinBoard(C2,R2)
   ;  C2 is C - 2, R2 is R + 1,
      withinBoard(C2,R2).

 withinBoard(Col,Row):-
        Row < 9, Row > 0, Col < 9, Col > 0.

Solution

  • ?- C=C,knight(8,1,R,C).
       C = 3, R = 7
    ;  C = 2, R = 6.
    

    Both orders are fine and mean exactly the same.

    Many current Prolog systems print variables in the very order determined by read_term(Query, [variable_names(VN_list)]). which they use to read a term. So the variable that occurs leftmost is the first to print its answer substitution.

    In the past, some systems ordered VN_list by the name of the variables. Which actually did make sense as the order was left unspecified by the standard. In the meantime, this has been corrected in Cor.3. It seems your homework dates from an earlier time since 'C' @< 'R'. To get the very precise order, you now need to add an artificial goal in front. I took C=C which is always true.

    All that said, I do not believe that your instructor will insist on the very precise order.