Prolog:根据DCG从列表中生成术语



我有以下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
| ?-

最新更新