Reputation: 185
I'm trying to make a simple grammar parser that checks whether a specific sentence pattern is valid or not. the grammar rules are as follows:
terminals: circleplus, circleor, 1, 0
non-terminals: S; T
start symbol: S
production rules: S --> S circleplus T | S circleor T | T, and: T --> 0 | 1
sentence([]).
sentence([a, b, c|Tail]) :- checkHead(a), checkC(b), checkT(c), sentenceCheck(Tail).
sentenceCheck([]).
sentenceCheck([b, c|Tail]) :- checkC(b), checkT(c), sentenceCheck(Tail).
checkT(c) :- T(c).
checkC(b) :- C(b).
checkHead(a) :- Head(a).
C(circleor).
C(circleplus).
Head(0).
Head(1).
T(0).
T (1).
% ?- sentence ([[0 , circleor ,1] , circleplus ,1]) .
% ==> true
The bottom comments are what a sample input --> output would look like. Appreciate any help.
EDIT: (per response to my question)
sentence([]).
sentence([A, B, C|Tail]) :- checkHead(A), checkC(B), checkT(C), sentenceCheck(Tail).
sentenceCheck([]).
sentenceCheck([B, C|Tail]) :- checkC(B), checkT(C), sentenceCheck(Tail).
checkT(C) :- t(C).
checkC(B) :- c(B).
checkHead(A) :- head(A).
c(circleor).
c(circleplus).
head(0).
head(1).
t(0).
t(1).
Only now the query sentence([0, circleor, 1]).
returns false
when it should be true
. Any ideas?
Upvotes: 0
Views: 227
Reputation: 3783
In prolog variables start with a capital letter and constant terms start with a lowercase letter. You are getting the error because prolog expects the predicate to be a constant term rather than a variable.
sentence([]).
sentence([A, B, C|Tail]) :- checkHead(A), checkC(B), checkT(C), sentenceCheck(Tail).
sentenceCheck([]).
sentenceCheck([B, C|Tail]) :- checkC(B), checkT(C), sentenceCheck(Tail).
checkT(C) :- t(C).
checkC(B) :- c(B).
checkHead(A) :- head(A).
c(circleor).
c(circleplus).
head(0).
head(1).
t(0).
t(1).
The above changes will help but your sample input, output will not work as you are nesting the list. If you do not nest the list as follows it will work.
?- sentence([0, circleor, 1, circleplus, 1]).
true.
A solution even when the input is not flattened is :
sentence(A) :- t(A).
sentence([A, B, C]) :-
sentence(A),
c(B),
t(C).
c(circleor).
c(circleplus).
t(0).
t(1).
Upvotes: 1