/** --------------------------------------------------------- holds if the blank (0) is moved right successfully within one row ---------------------------------------------------------- */ move_right(CurrentBoard, NewBoard) :- append(PrevRows, CurrentRow, R1), append(R1, NextRows, CurrentBoard), move_right_within_row(CurrentRow, ChangedRow), append(PrevRows, ChangedRow, R2), append(R2, NextRows, NewBoard). /** --------------------------------------------------------- helper function holds if the blank (0) is moved right successfully assume only one blank exists ---------------------------------------------------------- */ move_right_within_row(CurrentRow, ResultingRow) :- append(Start, [0, X | End], CurrentRow), append(Start, [X, 0 | End], ResultingRow). init(d, [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 0, 15], [13, 12, 11, 14] ]). ?- move_right_within_row([9, 10, 0, 15],R). R = [9, 10, 15, 0] ; No ?- init(d, S), move_right(S, B). ERROR: Out of global stack