创建Prolog查询和答案系统

时间:2017-05-29 07:01:21

标签: prolog

我正在学习prolog而且我一直遇到问题。我正在提问并回答系统 例如,当我输入时,“汽车的颜色是蓝色的”。该程序将说“OK”并添加新规则,因此当被问及“汽车的颜色是什么?”时它会以蓝色回复 如果我说“汽车的颜色是绿色的”,它会回复“它不是。” 但每当我输入“汽车的颜色为蓝色”时,它返回true,错误的问题版本。有人可以直接指望去哪里吗?我不知道如何让程序说“它的蓝色”或任何

 input :-
    read_line_to_codes(user_input, Input),
    string_to_atom(Input,Atoms),
    atomic_list_concat(Alist, ' ', Atoms),
    phrase(sentence(S), Alist),    
    process(S).

statement(Statement) --> np(Description), np(N), ap(A),
{ Statement =.. [Description, N, A]}.

query(Fact) -->  qStart, np(A), np(N),
 { Fact =.. [A, N, X]}.


np(Noun) --> det, [Noun], prep.
np(Noun) --> det, [Noun].

ap(Adj) --> verb, [Adj].
qStart --> adjective, verb.

vp --> det, verb.   

adjective --> [what].
det --> [the].

prep --> [of].

verb -->[is].


%% Combine grammar rules into one sentence
sentence(statement(S)) --> statement(S).
sentence(query(Q)) --> query(Q).
process(statement(S)) :- asserta(S).
process(query(Q))     :- Q.

1 个答案:

答案 0 :(得分:1)

你真的很亲密。看看这个:

?- phrase(sentence(Q), [what,is,the,color,of,the,car]).
Q = query(color(car, _6930)) ;
false.

您已成功将句子解析为查询。现在我们来处理它:

?- phrase(sentence(Q), [what,is,the,color,of,the,car]), process(Q).
Q = query(color(car, 'blue.')) ;
false.

如您所见,您已正确统一。当你完成时,你只是没有做任何事情。我认为您需要做的就是将process/1的结果传递给某些内容以显示结果:

display(statement(S)) :- format('~w added to database~n', [S]).
display(query(Q)) :- Q =.. [Rel, N, X], format('the ~w has ~w ~w~n', [N, Rel, X]).

修改input/0以传递给display/1谓词:

input :-
    read_line_to_codes(user_input, Input),
    string_to_atom(Input,Atoms),
    atomic_list_concat(Alist, ' ', Atoms),
    phrase(sentence(S), Alist),    
    process(S),
    display(S).

现在,当您使用它时,您会得到一些结果:

?- phrase(sentence(Q), [what,is,the,color,of,the,car]), process(Q), display(Q).
the car has color blue.
Q = query(color(car, 'blue.')) ;
false.

?- phrase(sentence(Q), [the,siding,of,the,car,is,steel]), process(Q), display(Q).
siding(car,steel) added to database
Q = statement(siding(car, steel)) ;
false.

?- phrase(sentence(Q), [what,is,the,siding,of,the,car]), process(Q), display(Q).
the car has siding steel
Q = query(siding(car, steel)) ;
false.