Prolog: Logic Programming for Rapid Development

Careful use of domain-specific languages such as SQL and XSLT can dramatically ease development. David Chisnall looks at SWI-Prolog, an open-source implementation of a language used heavily in the AI community, and describes how it can help in development of knowledge-based systems.

Like this article? We recommend

Like this article? We recommend

A good programmer knows a lot of languages, and which one is particularly
suited to a task. Some languages work well in a lot of different settings, while
others are very domain-specific. XSLT, for example, is a Turing-complete
language that’s useful for translating XML documents into different
formats, but not a good choice for most other applications. Prolog is another
language that falls into this category. It’s a general-purpose language,
but one that’s particularly well-suited to some problems and very
difficult to use for others.

Prolog, short for PROgramming in LOGic, is a high-level language
based on predicate logic. A full explanation of predicate logic would take far
more space than this article is allowed. For now, if you’re unfamiliar
with predicate logic, think of a predicate as a function returning a Boolean
value.

NOTE

The examples in this article can be downloaded in the accompanying
source.zip.

Building Blocks

Like all good languages, Prolog is syntactically simple. There are four basic
components of the language:

Numbers.

Atoms are analogous to nouns—things that exist. A Prolog atom
begins with a lowercase letter.

Variables in Prolog have more in common with variables in
mathematics than with most other programming languages. In mathematics, you
can’t say x = 5, and then later say x = 6 in the same context. The same is
true of Prolog; variables can have only one value during their lifetime. To
distinguish variables from atoms, Prolog variables begins with capital
letters.

Predicates look a lot like functions in other languages. A simple
predicate simply asserts something:

isMammal(cat).

This line has two components. The first is the predicate name, isMammal. In documentation, this will usually be written as isMammal/1, meaning that it’s a predicate that takes one argument
(also called a unary predicate). The argument given here is an atom, cat. Note that neither the isMammal predicate nor the cat atom has any special semantic meaning to Prolog; you could just as
easily say isMammal(fish), and have valid Prolog. An English-speaking
human, however, would likely regard this statement as a bug.

You can define other predicates with similar structure easily in the same
file: