Next: Parsers Up: Syntax Previous: Writing a Grammar

Grammars in Prolog

The general formalism we have used above is based on Prolog's built in grammar formalism, known as direct clause grammars. Prolog allows you to write grammars directly using the notation above, but internally in translates it into ordinary Prolog rules. A rule such as:


  sentence --> noun_phrase, verb_phrase.

is translated internally into a form like:


  sentence(Words, Remainder) :-
        noun_phrase(Words, NPRemainder), 
        verb_phrase(NPRemainder, Remainder).

A grammar rule takes a list of words (or other items) as its first argument and instantiates its second argument to the remaining words once some of the list has been parsed using the rule. So ?- noun_phrase([john, hit, mary], X) would return X=[hit, mary].

You shouldn't need to fully understand this internal representation when using Prolog's grammar facilities - However, when checking whether a sentence parses (given a grammar like the ones in the last section) you have to give a query like the following:


  ?- phrase(sentence, [john, likes, mary]).


alison@
Fri Aug 19 10:42:17 BST 1994