Updated: 03 September 2023

Introduction to Prolog

Notes from Derek Banas’ Youtube

Cheatsheet

Prolog consists of a collection of facts and rules that can be queried

These rules are stored in a Database or Knowledgebase file

Installation

You can install Prolog using Chocolatey with

1
choco install swi-prolog

You can then open Prolog terminal which will be in your Start Menu, or you can look for the installation directory and add that to your path (preferred)

In my case the installation is here:

1
C:\Program Files\swipl\bin

You should then be able to run the swipl command from your terminal to start that up

You can close it with the halt. command

Hello Worlding

You can hello-world with the following in the swipl terminal

1
write('Hello World').

Or multiple lines with:

1
write('Hello World'), nl,
2
write('Bye World').

Note that statements end with a .

Creating a Knowledgebase

Facts and rules are stored in a .pl file, in our case we use db.pl

You can define a fact which consists of a predicate and atoms/arguments, these start with lowercase letters

A fact can be defined with something like:

1
loves(romeo, juliet).

A rule can be defined, for example juliet loves romeo if romeo loves juliet

1
loves(juliet, romeo) :- loves(romeo, juliet).

A database file can be loaded with the name of the file in [] as follows:

1
[db].

A variable is something that allows us to answer questions, these start with capital letters

1
loves(romeo, X).

Will return:

1
X = juliet

We can define some additional facts with the following code:

1
male(john).
2
male(jeff).
3
male(bob).
4
5
female(sally).
6
female(jenny).
7
female(amy).

You can view a listing of facts with the following command

1
listing.

Or all facts of a specific kind such as

1
listing(male).

You can view all the combinations of facts with

1
male(X), female(Y).

You can type ; to move to the next element

Rules are used to state that a fact depends on another fact, the :- is like saying if

Example, albert runs if happy

1
runs(albert) :-
2
happy(albert).

We can also have multiple conditions separated by a , (and)

1
dances(alice) :-
2
happy(alice),
3
with_albert(alice).

We can define or with making use of diffeent rules, such as:

1
dances(alice) :-
2
happy(alice).
3
4
dances(alice) :-
5
with_albert(alice).