An implementation of a Prolog compiler much like the one described in this chapter is provided with this book in the package COM.sootNsmoke.prolog. The compiler is contained in the class COM.sootNsmoke.prolog.PrologCompiler. It has a main that expects its arguments to be files containing Prolog assertions, like the ones shown in section 13.1. If you place the code from section 0 into a file within.P, you can compile it with
java COM.sootNsmoke.prolog.PrologCompiler within.P
This produces two class files: within_2.class and inside_2.class. The class names include the number of arguments. For example, inside becomes inside_2 and within becomes within_2. This is because real Prolog allows you to write rules with the same name but different numbers of arguments. Rules composed this way have different heads; they answer different questions (compare with the Java method overloading).
There are several differences between the code shown in this chapter and the code produced by the compiler. The differences were introduced to make the discussion in this chapter simpler.
The stack trail is contained within the class Prolog. Each compiled rule requires an instance of this class. Usually, all rule instances share the same instance of Prolog. This eliminates the need for static variables in Prolog. (Static variables tend to make threading difficult, as well as other software engineering difficulties, so I try to avoid them.)
An additional data type is supported: cons cells. Cons cells are familiar to Lisp and Scheme programmers as the basic data type for building up data structures. They are most commonly used in Prolog for building up lists. There is a special Prolog syntax for lists:
[alpha, bravo, charlie]
This is really a set of three cons cells. The head of the first cell is alpha, and the tail is the list [bravo, charlie].
You can also write a list with the head of the list separated from the tail of the list by a vertical bar (|). The list above is equivalent to
[alpha | [bravo, charlie]]
[alpha | [bravo | [charlie]]]
Lists may contain variables. For example, if you had the rule
list([alpha, bravo, charlie]).
and you ask,
?- list([X | Y]).
X = alpha, Y = [bravo, charlie].
To make asking questions easier, a trivial Prolog interpreter is provided as the main of Prolog. It accepts only a single term. When it starts, it prints the prompt
You may type in your question at the prompt, like list([X | Y]). It prints the list of answers, then gives another prompt. You may use any rules that have previously been compiled.