带参数的Prolog DCG

时间:2019-05-14 17:15:47

标签: prolog arguments dcg

我不知道如何使用参数使用DCG。假设我们要使用DCG代表父母及其子女,那么我们可以说:

father --> [Peter].
mother --> [Isabel].

child --> [Guido].
child --> [Claudia].

verb --> [is].
relation --> [father, of].
relation --> [mothter, of].

s --> father, verb, relation, child.
s --> mother, verb, relation, child.

然后您可以通过以下方式查询:?- s([Peter, is, father, of, Guido], []).,它返回true

如何通过说出father(name)来在DCG上使用参数。

1 个答案:

答案 0 :(得分:2)

添加参数很容易,如果您按如下所示进行操作,我也不会感到惊讶,但是却无法使查询正常工作。诀窍在于,知道将DCG转换为常规Prolog时,会在将每个谓词转换为Prolog时将两个额外的参数穿线。可以根据自己的喜好命名它们,我个人更喜欢使用var arr = [1, 2, 3]; var check = [3, 4, 5]; var found = false; for (var i = 0; i < check.length; i++) { found =arr.indexOf(check[i]) > -1 ? true : false } alert(found); S0来表示状态,但是如果它们具有更具体的含义,请更改它们。

在以下代码中也要注意,由于名称以大写字母开头并且必须是原子,因此原子不用S进行预订,例如, peter

'

现在要检查您的第一个查询:

'Peter'

对于其他阅读本文的人来说,这是相同的答案,但未添加参数。如有疑问请检查。

现在使用添加的隐藏参数进行父查询。

father('Peter') --> ['Peter']. 
mother('Isabel') --> ['Isabel'].

child('Guido') --> ['Guido']. 
child('Claudia') --> ['Claudia'].

verb(is) --> [is]. 
relation('father of') --> [father, of]. 
relation('mother of') --> [mother, of].

s --> father(Father), verb(Verb), relation(Relation), child(Child). 
s --> mother(Father), verb(Verb), relation(Relation), child(Child).

您也可以这样做

?- s([Peter, is, father, of, Guido], []).
true ;
true ;
true ;
true.

旁注:

一个更好的方法是使用phrase/2phrase/3,我说使用而不回答,因为您问了有关如何查询子句父亲的问题,而不是用它来解析数据或使用短语谓词。

?- father(Father,S0,S).
Father = 'Peter',
S0 = [_5662|S].

?- father(Father,_,_).
Father = 'Peter'.

这些也可以

test :-
    DCG = father(Father),
    phrase(DCG,Input,Rest),
    format('Father: ~w~n',[Father]).

?- test.
Father: Peter
true.

如果使用listing/0,则可以看到DCG转换为Prolog,它将显示通过谓词穿线的两个额外参数。

?- phrase(father(Name),_).
Name = 'Peter'.