2016-07-15 108 views
1

我决定开始玩Prolog(SWI-Prolog)。我写了一个程序,现在我正在尝试编写一个简单的主谓词,以便我可以创建一个.exe并从命令行运行该程序。这样,我可以从命令行找到真实/错误的关系,而不是从prolog GUI。但是,我无法理解主谓词中究竟发生了什么。以下是节目至今:Prolog中的简单主谓词示例

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调用从主该功能。进入命令行。我希望能够开始寻找关系像我一样,我创建的谓词前,而是在程序启动与此错误:

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).),它应该找到这些变量之间的关系。当我打电话给主人时,至少我会希望节目等待我进入关系,返回结果,然后关闭。为什么这不起作用?

问题2:
我该如何写一个主谓语?这样的程序有没有好的例子?我试过here这个例子,但是无法启动它。

感谢您的任何帮助。

编辑:
新的尝试 - main.返回false,并运行main.返回false即使它应该是真实的之后运行parent(tim, anna).

:- 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状态,需要有电话之间的逗号。例如:

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)). 
+2

一个意见:考虑使用'mother_child/2','father_child/2'和'parent_of/2 '清楚地表示每个论点的含义。这会使你的代码更易读**,更容易为你和其他人考虑。这个语法错误源于尝试将一个谓词的定义嵌入到另一个谓词中,这是不可能的。 – mat

回答

2

我认为应该(不允许空参数列表)上的命名

:- dynamic mother/2. 
... other dynamically defined relations... 

family_func:- 
    assert(mother(tim, anna)). 
    ... 

% rules can be dynamic as well, it depends on your application flow... 
parent(X,Y) :- mother(X,Y). 
    ... 

main:- 
    family_func. 
+0

嗨。感谢您的回复。一旦我运行main,我仍然遇到运行命令的麻烦。当我打电话给main时,它会打印错误。然后,如果我尝试跑父母(蒂姆,安娜)。在main之后,我得到这个错误:ERROR:parent/2:Undefined procedure:mother/2 Exception:(8)mother(tim,anna)? – JustBlossom

+0

你忘了': - 动态母亲/ 2.'声明? – CapelliC

+0

在我刚刚解释的错误版本中,我将其排除了。那是因为当我使用动态时,一切都返回false。我将我在编辑中尝试的内容放到了我的问题中。 – JustBlossom