[Prolog UML Classes PIC]

A Prolog Interpreter in Java

 

Prolog.jar contains the source code and compiled Java for the classes shown in the diagram on the right. They represent a simple Prolog interpreter, closely based on one coded in C++ by Alan Mycroft back in 2000.

Incidentally, a JAR is just a form of zipped file, so can be examined with a tool such as 7-zip.

I have translated Mycroft's code into Java, and simplified things a little bit, mostly by using Java's collection classes.

Most of the classes represent syntactic elements of a simplified Prolog, which can be defined using the following BNF:

   Var  ::=  String
   Functor  ::=  String [ '(' Term { ',' Term  } ')' ]
   Term  ::=  Var | Functor
   Clause  ::=  Functor [ ':-' Functor { ',' Functor } ]

The [ ... ] notation means 0 or 1, and { ... } means 0 or more.

There's no Program or Query BNF rules since a program is represented by a list of clauses in the Java code, and a query is a list of functors.

The Trail class acts as a temporary store for variable bindings, so that they can be reset when execution backtracks.

The crucial method is solve() in Engine which implements Prolog's backtracking using backtracking in Java (i.e. recursion inside a loop).

The easiest way to get a feel for how the interpreter operates is to look through the three examples: Test1.java, Test2.java, and Test3.java

Download Prolog.jar and the three test programs, and compile and run them like so:

> javac -cp Prolog.jar;. Test1.java

> java -cp Prolog.jar;. Test1
 

A more direct translation of Mycroft's Prolog interpreter into Java was created by wrmsr a few years ago. Here's a version recoded in Python by cheery and Dmiles.


Dr. Andrew Davison
E-mail: ad@fivedots.coe.psu.ac.th
Back to my home page