user3277930
user3277930

Reputation: 87

Creating a Prolog Query and Answer System

I'm learning prolog and I've been stuck on a problem. I'm making a question and and answer system.
For example, When I type, "The color of the car is blue." The program will say "OK" and add that new rule, so when asked, "What is the color of the car?" It'll respond with blue.
If I say "the color of the car is green," it'll reply with "Its not." But whenever I type "The color of the car is blue" it returns true, false for the question version. Can someone direct on where to go further? I don't know how to get the program to say "its blue" or anything

 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.

Upvotes: 3

Views: 380

Answers (1)

Daniel Lyons
Daniel Lyons

Reputation: 22803

You're actually really close. Take a look at this:

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

You've successfully parsed the sentence into a query there. Now let's process it:

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

As you can see, you properly unified. You just didn't do anything with it when you were done. I think all you need to do is pass the result of process/1 into something to display the result:

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]).

And modify input/0 to pass to the display/1 predicate:

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).

Now you get some results when you use it:

?- 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.

Upvotes: 1

Related Questions