Prolog in Python - Introduction

Someone once made the remark that there were only two kinds of programming languages, Lisp and all the others. At that time the primary languages like Fortran were much more machine centric than those of today. That is, the way you programmed was, although more efficient, not too different than how you would program in machine language. Lisp with dynamic data, automatic garbage collection, and the ability for a lisp program to easily create and run more lisp code was very much an exception.

However over time, modern languages, like Python, came to support the kind of features found in Lisp. Today, the above remark might be changed to "Prolog and all the others".

The motivation for this project has been to deepen my own understanding of Prolog and hopefully share some of what I learn with others. The program is too slow to be used for any real world programming. But the ability to play with the source, add new features, maybe sprinkle print statements or use the trace feature when something is obscure is invaluable. Lots of real Prolog interpretors can be found on the internet. Or if someone is interested, porting this code to C++ would increase the speed considerably.

Project Development

I developed this code from scratch several years ago through trial and error (lots and lots of error) and did not look at any other implementation. Frankly, I wanted to solve the puzzle instead of looking up the answer. But after thrashing around for awhile I found I did need a hint. That hint led to the use of the goal stack processed from a loop (function "search"). Once I started doing that things started to fall into place.

The program is built in three versions, each expanding on its predecessor. From the start I assumed that a single complete program would be too much to make work at one go. And also too much to explain.

Version one contains the essential goal searching logic and storage of rules. Terms remain very simple.

Version two allows nested terms which make lists possible and also supports the square bracket syntax for lists.

Version three provides some arithmetic and comparison operations as well as the "cut" and "fail" operators.

Additional Resources

Lots of information and real Prolog interpreters (and even compilers) are available on the internet. A google search for "Prolog" will get you started.

I also found the Clocksin's book "Clause and Effect" a delightful read. It is short, only about 150 pages, but contains a good introduction to Prolog and some surprising case studies. It is not aimed at the beginning programmer, but if you find these pages digestable then his book may be right for you as well. The book was a strong motivator for me to start this website and also tweaked my interest in Logic circuits and the small compiler. Clocksin presents Prolog versions of similar programs.

Copyright © 2009-2021 Chris Meyers

* * *