2017-05-29 81 views
3

我正在学习prolog,并且一直困在一个问题上。我正在提出一个问题和答案系统。
例如,当我输入时,“汽车的颜色是蓝色的”。该程序会说“OK”,并添加新的规则,所以当被问及“车的颜色是什么?”时它会以蓝色回应。
如果我说“汽车的颜色是绿色的”,它会回答“它不是”。 但是,只要我输入“汽车的颜色是蓝色的”,它将返回true,对于问题版本为false。有人可以指导哪里走得更远吗?我不知道如何让程序说“它的蓝色”或任何创建一个Prolog查询和答案系统

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. 
+0

于没有跟踪你的查询,看看笏是错误的?而不是'? - Query.',只需写入'? - trace,Query.'并逐步完成。但是,但请不要忽略警告我知道他们只是警告,但如果你忽略警告,甚至忽略错误,然后你只是来到Stackoverflow,那么如果有人警告你,你犯了一个错误有什么区别? – 2017-05-29 08:24:21

+0

您有几个* singleton *变量警告和语法错误,所以需要在取得更多进展之前解决。 – lurker

+0

我已经拿出了错误,除了描述,因为我不知道我应该改变它。我不需要这个变量。有人可以指导我解决我原来的问题吗? – user3277930

回答

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.