Warning: This recogniser is far from being an optimised implementation. It is intended for teaching use only.
Note that the grammar used in this example is completely integrated into the program:
Note that this compiled grammar style is not very suitable for continuous development purposes. It would be much better to develop the grammar as context-free rules, and write a translation program which compiles the grammar into a program, adding all the necessary procedural details.
// cf_recog_td_lr_nd_com.pc
// D.Gibbon, 9 Nov 2001
// Utilities
first(string s){
int firstlen;
string f;
firstlen=strstr(s," ",0);
if(firstlen==-1)
f=s;
else
f=strleft(s,firstlen);
return f;
}
rest(string s){
int firstlen;
string r;
firstlen=strstr(s," ",0);
if(firstlen==-1)
r="";
else
r=strright(s,strlen(s)-firstlen-1);
return r;
}
// Pre-terminal (lexical) rules
v(string in){
string f,r,out;
f=first(in);r=rest(in);
if(f=="saw"||f=="met"||f=="laughed")
out=r;
else
out="!";
return out;
}
n(string in){
string f,r,out;
f=first(in);r=rest(in);
if(f=="dog"||f=="cat")
out=r;
else
out="!";
return out;
}
adj(string in){
string f,r,out;
f=first(in);r=rest(in);
if(f=="small"||f=="big"||f=="black")
out=r;
else
out="!";
return out;
}
det(string in){
string f,r,out;
f=first(in);r=rest(in);
if(f=="the"||f=="this"||f=="a")
out=r;
else
out="!";
return out;
}
// Non-terminal (phrasal) rules
nom(string in){
string out;
if(in=="!")
out=in;
else {
out=nom(adj(in));
if(out=="!")
out=n(in);
}
return out;
}
np(string in){
string out;
if(in=="!")
out=in;
else {
out=nom(det(in));
if(out=="!")
out=nom(in);
}
return out;
}
vp(string in){
string out;
if(in=="!")
out=in;
else {
out=np(v(in));
if(out=="!")
out=v(in);
}
return out;
}
s(string in){
string out;
out=vp(np(in));
return out;
}
main(){
string in,out;
in="the big big black dog saw a cat";
while(in!=""){
in=getsd("Input: ",in);
if(in!=""){
out=s(in);
if(out=="")
puts("Accepted!"+"\n");
else
puts("Rejected!"+"\n");
}
}
}
Tasks: