n-queens 解决方案在 Prolog 中不起作用

n-queens solution not working in Prolog

我正在尝试 运行 遵循 N-Queens Problem‍​..How far can we go? to find solutions to n-queens problem 中的代码:

generate([],_).
generate([H|T],N) :- H in 1..N , generate(T,N).
lenlist(L,N) :- lenlist(L,0,N).
lenlist([],N,N).
lenlist([_|T],P,N) :- P1 is P+1 , lenlist(T,P1,N).

queens(N,L) :-
        generate(L,N),lenlist(L,N),
        safe(L),!,
        labeling([ffc],L).

notattack(X,Xs) :- notattack(X,Xs,1).
notattack(X,[],N).
notattack(X,[Y|Ys],N) :- X #\= Y,
                         X #\= Y - N,
                         X #\= Y + N,
                         N1 is N + 1,
                         notattack(X,Ys,N1).

safe([]).
safe([F|T]) :- notattack(F,T), safe(T).

我在 Debian-9(稳定版)Linux 上安装了 swi-prolog,我正在 运行上面使用命令 "swipl -f nqueens.pl"。加载时出现错误:

Syntax error: operator expected (probably on 2nd code line)

问题出在哪里,如何解决?感谢您的帮助。

当我查看第 2 行时,如错误消息所示,最可能的原因是 H in 1..N。我会把它写成 between(1, H, N)。不过,我最近没有在 Prolog 中做过任何事情。

Prolog 有几种不同的实现,它们在这些小细节上有所不同。尝试搜索 编写可移植 Prolog 代码.

的指南

题中其实提到写在CLPFD (A Constraint L ogic Programming 工具在 Finite Domains)。您必须导入此库:

<b>:- use_module(library(clpfd)).</b>

generate([],_).
generate([H|T],N) :- H in 1..N , generate(T,N).
lenlist(L,N) :- lenlist(L,0,N).
lenlist([],N,N).
lenlist([_|T],P,N) :- P1 is P+1 , lenlist(T,P1,N).

queens(N,L) :-
        generate(L,N),lenlist(L,N),
        safe(L),!,
        labeling([ffc],L).

notattack(X,Xs) :- notattack(X,Xs,1).
notattack(X,[],N).
notattack(X,[Y|Ys],N) :- X #\= Y,
                         X #\= Y - N,
                         X #\= Y + N,
                         N1 is N + 1,
                         notattack(X,Ys,N1).

safe([]).
safe([F|T]) :- notattack(F,T), safe(T).

然后它开始工作,并产生例如:

?- queens(5,L).
L = [1, 3, 5, 2, 4] ;
L = [1, 4, 2, 5, 3] ;
L = [2, 4, 1, 3, 5] ;
L = [2, 5, 3, 1, 4] ;
L = [3, 1, 4, 2, 5] ;
L = [3, 5, 2, 4, 1] ;
L = [4, 1, 3, 5, 2] ;
L = [4, 2, 5, 3, 1] ;
L = [5, 2, 4, 1, 3] ;
L = [5, 3, 1, 4, 2].