2017-05-29 84 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.