list - Prolog:根据 DCG 从列表中生成一个术语

标签 list prolog dcg parse-tree

我有以下 DCG:

s   --> np, vp.

np  --> det, n.

vp  --> v.

det --> [the].

n   --> [cat].

v   --> [sleeps].

我可以验证像 s([the,cat,sleeps], []) 这样的句子,并且我得到回复“yes”。

但我需要将这句话作为一个术语,例如:s(np(det(the),n(cat)),vp(v(sleeps)))

我怎样才能从列表 [the,cat,sleeps] 中生成术语?

最佳答案

您只需要扩展当前的 DCG 以包含一个定义您所追求的术语的参数:

s(s(NP, VP))  -->  np(NP), vp(VP).

np(np(Det, Noun))  -->  det(Det), n(Noun).
vp(vp(Verb))  -->  v(Verb).

det(det(the))  -->  [the].

n(n(cat))  -->  [cat].

v(v(sleeps))  -->  [sleeps].

然后你用phrase调用它:

| ?- phrase(s(X), [the, cat, sleeps]).
X = s(np(det(the),n(cat)),vp(v(sleeps)))

代码可能看起来有点困惑,因为您想要的术语名称恰好与您选择的谓词名称相匹配。重命名谓词,使其更清晰:

sentence(s(NP, VP))  -->  noun_part(NP), verb_part(VP).

noun_part(np(Det, Noun))  -->  determiner(Det), noun(Noun).
verb_part(vp(Verb))  -->  verb(Verb).

determiner(det(the))  -->  [the].

noun(n(cat))  -->  [cat].

verb(v(sleeps))  -->  [sleeps].

| ?- phrase(sentence(X), [the, cat, sleeps]).
X = s(np(det(the),n(cat)),vp(v(sleeps)))

如果您想通过例如包含更多名词来扩充它,您可以这样做:

noun(n(N)) --> [N], { member(N, [cat, dog]) }.

一般的查询结果:

| ?- phrase(sentence(X), L).

L = [the,cat,sleeps]
X = s(np(det(the),n(cat)),vp(v(sleeps))) ? a

L = [the,dog,sleeps]
X = s(np(det(the),n(dog)),vp(v(sleeps)))

(1 ms) yes
| ?-

关于list - Prolog:根据 DCG 从列表中生成一个术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34666284/

相关文章:

prolog - 使用 DCG 解析表达式

regex - 正则表达式匹配序言

prolog - 如何定位过度扩展目标的原因?

c++ - OSX 10.8 上 C++ 中列表内存泄漏的 vector

list - Prolog 查找列表中的中间元素

C++列表遍历和初始化

list - 如何在数独游戏的序言列表中设置值

Prolog查找所有匹配条件的子集

python - 如何将单词 'and'添加到返回的字符串列表中

prolog - 写入未命名变量