2.2. Introductory TOY(FD) Examples 25
N queens in a chessboard in such a way that no queen attacks each other. Observe the
use of the directive include to make use of both the FD constraint functions and the
function length/1 (predefined in the file misc.toy).
include "cflpfd.toy"
include "misc.toy" %%To use length/1
queens :: int -> [int] -> [labelingType] -> bool
queens N L Label = true <==
length L == N,
domain L 1 N,
constrain_all L,
labeling Label L
constrain_all :: [int] -> bool
constrain_all [] = true
constrain_all [X|Xs] = true <==
constrain_between X Xs 1,
constrain_all Xs
constrain_between :: int -> [int] -> int -> bool
constrain_between X [] N = true
constrain_between X [Y|Ys] N = true <==
no_threat X Y N,
N1 == N+1,
constrain_between X Ys N1
no_threat:: int -> int -> int -> bool
no_threat X Y I = true <==
X #\= Y,
X #+ I #\= Y,
X #- I #\= Y
Again, if we compile and load this program, we can solve goals as the following:
TOY(FD)> queens 4 L [ff]
yes
L == [ 2, 4, 1, 3 ]
Elapsed time: 0 ms.
more solutions (y/n/d) [y]?
yes
L == [ 3, 1, 4, 2 ]
Kommentare zu diesen Handbüchern