考虑以下列表:
[my,name,is,jack,baur]
我想将其统一为以下模式:
[my,name,is,Name]
这样变量 Name 最后的值为“jack baur”。 该变量在这里充当某种通配符,并且应该与未知数量的原子/列表成员统一。
重要:
- 变量/通配符并不总是位于末尾
- 可以有多个变量/通配符
目前我有这样的东西:
rule([my,name,is,Name],[hello,Name]).
% Sentence is a list (e.g. [my,name,is,jack,baur]
answer(Sentence,Response) :-
rule(Sentence,ResponseList),
atomic_list_concat(ResponseList,' ',Response).
显然,这只在 Name
恰好是一个单词而不是两个单词时才有效。
我如何在 Prolog 中解决这个问题?
最佳答案
这里有 DCG 的可能性。我认为它相当干净。
list(L) --> {length(L, _)}, L.
rule(R) -->
[my, name, is], list(Name),
[and, i, live, in], list(Country),
{flatten([hello, Name, of, Country],R)}.
rule([hello|Name]) -->
[my, name, is], list(Name) .
answer(Sentence, Response) :-
phrase(rule(Response), Sentence), !.
这样
?- answer([my, name, is, bill, the, kid, and, i, live, in, new, york],R).
R = [hello, bill, the, kid, of, new, york].
这里的基本产生式是 list//1,它匹配任何标记的确定长度列表。
注意:list(A),list(B),
,应避免 A、B 均未绑定(bind)。
如果中间有标记也没关系,例如 list(A),[and],list(B),
关于list - 通过连接原子来统一不同长度的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14031084/