Prolog中的简单主谓词示例

时间:2016-07-15 06:39:11

标签: prolog

我决定开始玩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,并在运行parent(tim, anna).后立即运行main.,即使它应该为true,也会返回false。

:- 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)).

1 个答案:

答案 0 :(得分: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.