Thursday 9 February 2023

1 - Simple Facts



Let's start with the simplest task, creating and querying facts.

Have a look at the following short prolog program.


% Example 01 - Creating & Querying Facts

% simple facts
tasty(apple).
tasty(banana).
tasty(cherry).

Lines beginning with % are comments for us to read, and are ignored by prolog.


Creating Facts

Let's look at the first real line of code.


tasty(apple).

This creates a simple fact, which then sits in prolog's database waiting to become useful later.

This fact consists of two parts, tasty() and apple. It is saying that a thing called apple, has a property called tasty.

Of course, calling the thing apple doesn't necessarily mean it is an apple. We could have typed elephant instead of apple. Similarly, the property tasty is just a word we've chosen.

Even so, it is useful to imagine we're describing real apples and genuine tastiness. We'll see later that this imagining becomes more useful the better we describe things and their properties in code.

The remaining two lines of code create new facts to sit in the database, tasty(banana), and tasty(cherry).


Querying The Database

Having established a small database of facts, we can query it.


?- tasty(apple).

Here we are asking “does the thing called apple satisfy the property called tasty?” Or more simply, “are apples tasty?”

Prolog tries to answer this question by searching the database. In our database it quickly finds the fact tasty(apple). This matches our query, and so prolog responds by saying true.


?- tasty(apple).

true

If we ask whether a banana is tasty, prolog will again respond with true, because tasty(banana) is a fact in our database.


?- tasty(banana).

true

What would happen if we asked whether a mango is tasty?

You and I might both agree that mangos are indeed tasty, but prolog can't say that because it isn't stated in the database. Prolog won't say “I think so”, or “maybe”. It will always say false, unless it can prove something is true.


?- tasty(mango).

false

Key Points

  • The basis of a prolog program is a database of facts.
  • Facts consist of two parts, a thing, and a property of that thing. 
  • We interact with prolog through queries, asking whether a statement is true.
  • Prolog determines the truth of a query statement by searching its database.