gpt4 book ai didi

Prolog:从 DCG 生成查询

转载 作者:行者123 更新时间:2023-12-03 22:18:48 27 4
gpt4 key购买 nike

我目前有一个包含几个人和一些关系谓词的小型 Prolog 数据库。例如:

female(anna).
female(susan).

male(john).
male(timmy).

siblings(anna, susan).
siblings(anna, john).
siblings(susan, john).

sibling(X, Y) :- siblings(X, Y) ; siblings(Y, X).

%X is brother of Y
brother(X, Y) :- male(X), sibling(X, Y).

我有一个 DCG 可以确定有效的问题,例如
“谁是约翰的兄弟”,这也很好用。
question --> ip, verb, article, noun, pronoun, name.

现在我想让我的程序用这样的名词和名字来调用我的家庭数据库:
noun(X, name).

在这个例子中应该是
brother(X, anna).

然后将答案作为自然语言答案返回,例如:
"the brother of anna is john"

定义答案句的语法也没有问题。我唯一不知道的是,如何从我的 DCG 调用到我的数据库并在其中填充正确的值。我现在环顾四周 - 也许我不知道正确的搜索词 - 并且找不到与此相关的内容。

我希望你们有一些好主意! :)

谢谢你。

最佳答案

从 DCG 调用 Prolog 谓词

常规方式:使用{}/1
使用非终结符 {}//1从 DCG 中调用任意 Prolog 目标。

例如:

verb --> [V], { verb(V) }.

这定义了一个非终结符 verb//1 .此 DCG 描述了一个由元素 V 组成的列表。使得 verb(V)持有,其中 verb/1是一个普通的 Prolog 谓词。

从某种意义上说,甚至更规律:始终使用 DCG!

请注意,还有第二种方法可以做到这一点,从某种意义上说,它更容易理解:您可以简单地转 。一切进入 DCG 非终端!

例如,你可以说:
female(anna)  --> [].
female(susan) --> [].
male(john) --> [].
male(timmy) --> [].

然后您可以直接使用这些非终结符。你可以定义一个 term_expansion/2自动执行此类转换的规则。

在您的特定情况下,使用 {}/1可能更可取,因为您已经拥有现有的 Prolog 事实和。但是在某些情况下,最好始终使用 DCG。

编辑 :从您的评论中,我看到您的问题涉及更多。

问题是关于:

从句子构建 Prolog 目标

这是非常直接的:本质上,您只需要描述 关系在你想要的 Prolog 目标和相应的句子之间。

我们通过向 DCG 引入一个新参数来实现这一点,该参数将表示需要执行以回答句子的 Prolog 目标。在您的示例中,您想将句子“谁是苏珊的兄弟?”与 Prolog 谓词的调用 brother(X, susan) 相关联。 .您已经有一个非终结符 sentence//0描述这样的句子。你只需要明确这些句子对应的目标。例如:
sentence_goal(noun(X, name)) --> ip, v, a, noun, p, name.

This is only used to illustrate the principle; I'm not claiming that this is already the full solution. The point is simply to show that you can reason about Prolog goals in exactly the same way as about all other terms.

You can then invoke the actual goals in two phases:

  1. first, relate the given sentence to the goal, using this new nonterminal sentence_goal//1
  2. simply call the goal, using call/1 or invoking it directly.

For example:

?- phrase(sentence_goal(Goal), Sentence), Goal.

在您的情况下,剩下的就是将这些句子与您要调用的 Prolog 目标相关联,例如 brother_of/2等等。

这一切都不需要任何副作用( write/1 )!相反,专注于描述 关系 在句子和目标之间,让 Prolog 顶层为您打印。

关于Prolog:从 DCG 生成查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36673733/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com