Prolog解数独
我是Prolog的新手,在swi-Prolog.org上找到了这个例子来解决数独问题。但我不能运行它。我查找了相同的长度,只有Prolog解数独,prolog,sudoku,swi-prolog,constraint-programming,clpfd,Prolog,Sudoku,Swi Prolog,Constraint Programming,Clpfd,我是Prolog的新手,在swi-Prolog.org上找到了这个例子来解决数独问题。但我不能运行它。我查找了相同的长度,只有相同的长度/2没有相同的长度/1。还有all_distinct/2和notall_distinct/0 以下是我的错误: ERROR: d:/.../prolog/sudoku.pl:5:10: Syntax error: Operator expected % d:/.../prolog/sudoku compiled 0.00 sec, 0 clauses Warni
相同的长度/2
没有相同的长度/1
。还有all_distinct/2
和notall_distinct/0
以下是我的错误:
ERROR: d:/.../prolog/sudoku.pl:5:10: Syntax error: Operator expected
% d:/.../prolog/sudoku compiled 0.00 sec, 0 clauses
Warning: The predicates below are not defined. If these are defined
Warning: at runtime using assert/1, use :- dynamic Name/Arity.
Warning:
Warning: all_distinct/1, which is referenced by
Warning: d:/.../prolog/sudoku.pl:16:8: 2-nd clause of blocks/3
以下是SWI Prolog示例的代码:
use_module(library(clpfd)).
sudoku(Rows) :-
length(Rows, 9), maplist(same_length(Rows), Rows),
append(Rows, Vs),
Vs in 1..9,
maplist(all_distinct, Rows),
transpose(Rows, Columns),
maplist(all_distinct, Columns),
Rows = [As,Bs,Cs,Ds,Es,Fs,Gs,Hs,Is],
blocks(As, Bs, Cs),
blocks(Ds, Es, Fs),
blocks(Gs, Hs, Is).
blocks([], [], []).
blocks([N1,N2,N3|Ns1], [N4,N5,N6|Ns2], [N7,N8,N9|Ns3]) :-
all_distinct([N1,N2,N3,N4,N5,N6,N7,N8,N9]),
blocks(Ns1, Ns2, Ns3).
problem(1, [[_,_,_,_,_,_,_,_,_],
[_,_,_,_,_,3,_,8,5],
[_,_,1,_,2,_,_,_,_],
[_,_,_,5,_,7,_,_,_],
[_,_,4,_,_,_,1,_,_],
[_,9,_,_,_,_,_,_,_],
[5,_,_,_,_,_,_,7,3],
[_,_,2,_,1,_,_,_,_],
[_,_,_,_,4,_,_,_,9]]).
我希望你能帮我找到我的错误。据我所知,它现在已经对你有用了。然而,我仍然想借此机会向您展示一些可能对您有用的提示: 事实与指令 首先,为什么您在答案中发布的代码不起作用 Prolog消息已经给出了一个很好的指示: Warning: The predicates below are not defined. ... ... all_distinct/1, which is referenced by 与您可能相信的相反,这不会导入库!为什么?因为,就目前而言,这只是一个形式为
use\u module/1
的序言,类似于以下事实:
name(bob).
这是一个形式为:-(T)
的术语,在加载文件时将作为指令处理
便利定义
就我个人而言,我经常编写小型Prolog程序,其中大多数使用CLP(FD)约束。在某些时候,我厌倦了将:-use_module(library(clpfd))。
添加到我的所有程序中,因此我将以下定义添加到我的~/.emacs
:
(global-set-key "\C-cl" (lambda ()
(interactive)
(insert ":- use_module(library()).")
(forward-char -3)))
点位于()
中,因此您只需键入库的实际名称,而无需键入其:-use_module…等指令
因此,要使用库(clpfd)
,我只需键入:
C-c l clpfd
C-clpfd
过了一会儿,我也厌倦了这一点,只是简单地将:-use_module(library(clpfd)).
添加到我的~/.swiplrc
配置文件中,因为我编写的几乎所有程序都执行整数运算,所以我编写的所有prolog程序中都可以使用CLP(FD)约束。例如,在GnupLog和B-Prolog这样的系统中,情况也是如此
但是,我仍然保留了.emacs
定义,因为有时我需要导入其他库,并且我发现键入整个:-use\u module…
指令太麻烦而且容易出错。指向此代码的链接在哪里?我对地图列表(相同长度(行,行,行)的含义感到困惑。
。乍一看,它的其余部分对我来说并不疯狂。我把它添加到了描述中。我自己从网站上复制并粘贴了代码,它就工作了。在上次编辑中,您删除了我在先前评论中指出的打字错误;我建议您需要再次尝试复制粘贴代码,并在链接页面上运行查询,它将对您起作用。我使用swi Prolog,在sudoku.pl中将其复制为1,并查阅了此文件。但我还是觉得这个错误很有趣。不,它有效。但我一点也没变
(global-set-key "\C-cl" (lambda ()
(interactive)
(insert ":- use_module(library()).")
(forward-char -3)))
:- use_module(library()).
C-c l clpfd