【问题标题】:Simple Main Predicate Example in PrologProlog 中的简单主谓词示例
【发布时间】: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


【解决方案1】:

我认为应该是(不允许空参数列表)

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

【讨论】:

  • 嗨。感谢您的回复。运行 main 后,我仍然无法运行正在运行的命令。当我调用 main. 时,它打印为 false。然后,如果我尝试运行 parent(tim, anna)。在 main. 之后,我收到此错误:错误:父/2:未定义的过程:母亲/2 异常:(8)母亲(蒂姆,安娜)?
  • 您忘记了:- dynamic mother/2. 声明吗?
  • 在我刚刚解释的错误版本中,我将其遗漏了。那是因为当我使用动态时,一切都返回 false。我将我尝试过的内容编辑到我的问题中。
  • 抱歉,我的示例具有误导性...您需要在 调用 之间使用逗号,因此它应该为 family_func :- assert(mother(tim, anna)), ... 并且当您在内存数据库,您应该发出查询,这将导致真/假结果,当为真时,会将参数绑定到您感兴趣的值
  • 哦,原来如此!非常感谢你的帮助。我将在我的问题中记下调用语法之间的逗号,以便其他人知道(以防万一)。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多