SWI-PROLOG TUTORIAL
PROLOG PROGRAM
Prolog programs consist of fact (assumptions) and inference rules.
In Prolog, database or knowledgebase is a collection of facts.
PROLOG draws its knowledge from these facts.
Facts
Facts are statements that are true. Prolog treats Facts as true and enters them
into its knowledgebase.
Facts in the database/knowledgebase:
likes(joe, fish).
likes(joe, mary).
likes(mary, book).
likes(john, book).
Rules
Prolog rules are Horn clauses, but they are written “backwards”, consider:
∀X,Y[female(X) ∧ parent(X,Y) ⇒ mother(X,Y)]
is written in Prolog as
mother(X,Y) :- female(X) , parent(X,Y) .
head body
where, :- means Implies (“think of ⇐”)
You can think of a rule as introducing a new “fact” (the head), but the fact is
defined in terms of a compound goal (the body). That is, predicates defined as rules
are only true if the associated compound goal can be shown to be true.
Query
A query is a way to extract information from a logic program.
Given a query, Prolog attempts to show that the query is a logical consequence of the
program; of the collection of facts.
In other words, a query is a goal that Prolog is attempting to satisfy (prove true).
We execute Prolog programs by posing queries on its knowledgebase.
Queries:
Using the facts from previous slide, let’s make a query.
?- likes(joe, money).------------------- Query
no --------------------------- This is the response of Prolog to the query above.
?- likes(joe, mary).
yes
Using SWI-PROLOG
To make queries in SWI-Prolog, we must have a knowledgebase containing facts and rules.
- The knowledgebase is created and saved in an editor (e.g. notepad). For example: The
image below shows the knowledgebase created in the previous slide saved in a notepad file.
Using SWI-PROLOG
Queries are made in the SWI-Prolog application.
- The knowledgebase is first connected to SWI-Prolog using the “Consult” feature in the File
tab in the SWI-Prolog application. Open SWI-Prolog and connect to the knowledgebase
previously created in notepad.
Using SWI-PROLOG
Queries are made in the SWI-Prolog application.
- Click “Consult” and then navigate to the knowledgebase you’ve previously created in
notepad. Select the knowledgebase and click Open.
Using SWI-PROLOG
Queries are made in the SWI-Prolog application.
- After clicking Open, the knowledgebase is then successfully connected.
Note: If the text is colored red, it means there is some syntax error in the knowledgebase.
Using SWI-PROLOG
Queries are made in the SWI-Prolog application.
- Now queries can be made in SWI-Prolog.
Using SWI-PROLOG
Another Example:
Take a look at the following knowledgebase. It consists of facts, rules and clauses.
Using SWI-PROLOG
Another Example:
Connection to the knowledgebase is successful.
Using SWI-PROLOG
Another Example:
Queries:
Additional Resources:
SWI-Prolog YouTube Playlist: https://youtube.com/playlist?
list=PLEJXowNB4kPy3_qhGksOO8ch_Di7T8_9E