【发布时间】:2016-07-15 06:39:11
【问题描述】:
我决定开始使用 Prolog (SWI-Prolog)。我编写了一个程序,现在我正在尝试编写一个简单的主谓词,以便我可以创建一个 .exe 并从命令行运行该程序。这样,我可以从命令行而不是从 prolog GUI 中找到真/假关系。但是,我无法理解主要谓词中的实际内容。这是目前为止的程序:
mother(tim, anna).
mother(anna, fanny).
mother(daniel, fanny).
mother(celine, gertrude).
father(tim, bernd).
father(anna, ephraim).
father(daniel, ephraim).
father(celine, daniel).
parent(X,Y) :- mother(X,Y).
parent(X,Y) :- father(X,Y).
ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).
第一次尝试:
我将所有关系定义放在一个名为family_func() 的谓词中。然后,我尝试通过键入main 从main 调用该函数。进入命令行。我希望能够像创建谓词之前那样开始查找关系,但程序开始时出现以下错误:
ERROR: c:/.../ancestor.pl:18:0: Syntax error: Operator expected
代码如下:
family_func():-
mother(tim, anna).
...
parent(X,Y) :- mother(X,Y).
...
main:-
family_func().
第二次尝试:
我尝试将所有定义放在主要谓词中。我希望能够键入 main。然后让程序暂停并等待我开始输入子句(就像在 Java 中运行程序并等待用户输入一样)。相反,当我输入 main. 时,它返回 false。
问题 1:
我习惯用 Java 编写代码。所以,在我看来,我尝试的第一件事应该有效。我基本上在family_func() 中定义了局部变量,然后我调用了较小的“方法”(即parent(X,Y) :- mother(X,Y).)来查找这些变量之间的关系。当我调用 main 时,至少,我会期望程序等待我进入关系,返回结果,然后关闭。为什么这不起作用?
问题 2:
我将如何实际编写主要谓词?这样的程序有什么好的例子吗?我已经尝试了示例 here,但无法使其正常工作。
感谢您的帮助。
编辑:
新尝试 - main. 返回 false,并且在运行 main. 之后立即运行 parent(tim, anna). 返回 false,即使它应该为 true。
:- dynamic mother/2.
:- dynamic father/2.
family_func:-
assert(mother(tim, anna)).
assert(father(tim, bernd)).
parent(X,Y) :- mother(X,Y).
parent(X,Y) :- father(X,Y).
ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y).
main:-
family_func.
编辑:
以防万一其他人需要知道,正如@CapelliC 在答案下的 cmets 中所述,呼叫之间需要有逗号。例如:
family_func:-
assert(mother(tim, anna)),
assert(mother(anna, fanny)),
assert(mother(daniel, fanny)),
assert(mother(celine, gertrude)),
assert(father(tim, bernd)),
assert(father(anna, ephraim)),
assert(father(daniel, ephraim)),
assert(father(celine, daniel)).
【问题讨论】:
-
关于命名的一条评论:考虑使用
mother_child/2、father_child/2和parent_of/2来清楚地表示每个参数的含义。这将使您的代码更具可读性,并且更容易为您和其他人考虑。这些语法错误源于试图将一个谓词的定义嵌入到另一个谓词中,这是不可能的。
标签: prolog