0
votes

Here is a tiny lexicon and a minigrammar consisting of one syntactic rule, I have to list all the sentences that this grammar can generate in the order that Prolog will generate them in, I know that the first sentence would be: a criminal eats a criminal, but then I don't know how to find the other sentences, how does the Prolog interpreter works on these cases? I don't want you to give me all the answers, I just need a little clue.

word(determiner,a).
word(determiner,every).
word(noun,criminal).
word(noun,'big kahuna burger').
word(verb,eats).
word(verb,likes).

sentence(Word1,Word2,Word3,Word4,Word5):-
    word(determiner,Word1),
    word(noun,Word2),
    word(verb,Word3),
    word(determiner,Word4),
    word(noun,Word5).
2
Did you try running it? Prolog will look for all solutions to sentence that match the database.lurker

2 Answers

1
votes

Prolog has a relational data model, and uses the comma to mean AND. There are 2 choices for each word kind, then there will be 2 solutions for each word occurrence.

The next phrase generated will use the first alternative available, and since the execution model is depth first search, such alternative will be the next noun after criminal.

Now, since Prolog exhausted the alternatives for the last word, it will 'go back', to see if a different determiner is available. It will find every, then it will try - again - all alternatives for noun, etc etc

1
votes

As always when describing lists, consider using a DCG. Your code can be written like this with DCG nonterminals:

determiner --> [a].
determiner --> [every].

noun --> [criminal].
noun --> ['big kahuna burger'].

verb --> [eats].
verb --> [likes].

A "sentence" in your case is a list that is described with the following nonterminal:

sentence --> determiner, noun, verb, determiner, noun.

Notice that (,)//2 in DCGs can be read as "and then".

The sentences that are described with this grammar can then be enumerated with:

?- phrase(sentence, Ls).
Ls = [a, criminal, eats, a, criminal] ;
Ls = [a, criminal, eats, a, 'big kahuna burger'] ;
Ls = [a, criminal, eats, every, criminal] ;
etc.

where you press SPACE to see further solutions.