% Prolog representation of a context-free grammar for a very restricted subset of English
% This is slightly expanded code of Figures 13.7 & 13.8 in Section 13.6.1 of
% Poole and Mackworth, Artificial Intelligence: foundations of
% computational agents, Cambridge, 2017.
% Copyright (c) David Poole and Alan Mackworth 2017. This program
% is released under GPL, version 3 or later; see http://www.gnu.org/licenses/gpl.html
% a sentence is a noun phrase followed by a verb phrase.
sentence(L0,L2) :-
noun_phrase(L0,L1),
verb_phrase(L1,L2).
% a noun phrase is a determiner followed by adjectives followed
% by a noun followed by an optional prepositional phrase.
noun_phrase(L0,L4) :-
det(L0,L1),
adjectives(L1,L2),
noun(L2,L3),
pp(L3,L4).
% Try:
%?- noun_phrase([the,student,passed,the,computer,science,course],R).
%?- noun_phrase([the,new,computer,science,student,passed,the,course],R).
%?- noun_phrase([the,computer,science,course,with,a,computer],R).
% an optional noun phrase is either nothing or a noun phrase
opt_noun_phrase(L,L).
opt_noun_phrase(L0,L1) :-
noun_phrase(L0,L1).
% a verb phrase is a verb followed by a noun phrase and an optional pp
verb_phrase(L0,L3) :-
verb(L0,L1),
opt_noun_phrase(L1,L2),
pp(L2,L3).
% an optional prepositional phrase is either
% nothing or a preposition followed by a noun phrase
pp(L,L).
pp(L0,L2) :-
preposition(L0,L1),
noun_phrase(L1,L2).
% adjectives is a sequence of adjectives
adjectives(L,L).
adjectives(L0,L2) :-
adj(L0,L1),
adjectives(L1,L2).
% dictionary
det([a | L], L).
det([the | L], L).
det(L,L).
noun([student | L], L).
noun([course | L], L).
noun([computer | L], L).
noun([cat | L], L).
noun([mat | L], L).
noun([hat | L], L).
adj([practical | L],L).
adj([new | L],L).
adj([computer, science | L],L).
verb([passed | L],L).
verb([failed | L],L).
verb([sat | L],L).
preposition([with | L],L).
preposition([on | L],L).
% Example Query:
%?- sentence([the,new,computer,science,student,passed,the,course],R).
%?- sentence([the,student,passed,the,computer,science,course,with,a,computer],R).