The following small program is intended to illustrate the use of Prolog to solve a simple problem. The problem is a typical ``programming example'' , it is not a typical ``real world'' application. However this program is written in a way that exploits the attributes of Prolog.
The problem is to place eight chess queens on a chess board so that not one can attack any other.
eight(QS) :- perm([1,2,3,4,5,6,7,8],QS), safe(QS).
perm([],[]).
perm([H|T],P) :- perm(T,PT), insert(H,PT,P).
insert(X,L,[X|L]).
insert(X,[Y|L1],[Y|L2]) :- insert(X,L1,L2).
safe([]).
safe([Q|Rest]) :- safe(Rest), notattacked(Q,Rest,1).
notattacked(Y,[],Xoffset).
notattacked(Y,[Y1|YList],Xoffset) :-
Y1 - Y =\= Xoffset, Y - Y1 =\= Xoffset,
Nxoff is Xoffset + 1,
notattacked(Y,YList,Nxoff).
© University of Hertfordshire Higher Education Corporation (1998)