Logic Programming in Python – Pierre Carbonnelle

You are probably already using some logic programming in Python: SQL is in fact in many ways a logic programming language. However, for true logic programming, there is pyDatalog.

Logic programming is one of the three main programming paradigms, next to imperative and functional. Why logic programming? It’s more terse therefore more productive and more readable. You can follow the stream of thought rather than the sequence of execution, which makes it easier to write and to understand.

A logic program has facts (= entering data), clauses (= rules), and queries (= start executing). In pyDatalog, you set things up by enumerating the words (strings) that should be considered as facts, clauses and queries, and then you write them in a syntax that is very similar to Prolog. In the same way, you can also use existing Python functions and variables. It is also possible to use tuples with the typical slicing notation. The syntax doesn’t feel pythonesque so it still is a different language really, but pyDatalog makes it possible to mix the two easily and to use the full power of Python packages from within a logic program.

The logic concepts are combined with OO, using pyDatalog.Mixin: inherit from that class and then you can use logic statements with instances of that class.

The language has input/output polymorphism: clauses are defined independent of the types of their operands, so the same logic can be reused for different types.

The language uses memoization: intermediate results are stored. This helps to avoid infinite loops, and also makes solving faster. This is currently done query per query, so when a query finished the results are cleared. In the future this will be extended, but that requires the concept of transactions to be able to roll back.

There is no equation solver yet (so it is not constraint logic programming), but that can be added fairly easily.

A possible extension is to use a relational database to store the facts, clauses and results, since these are optimized for looking up these things and that is what a solver has to do all the time.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s