Install SWI-Prolog interpreter with sudo snap install swi-prolog
.
Start it with swi-prolog.swipl
.
Basic Syntax
A clause is ended with full stop (period).
Text between /*
and */
is comment and is ignored.
Notes of LPP
Notes of book "Logic Programming with Prolog", 2nd edition by Max Bramer.
1.1
BIP: built-in predicates, like write
, nl
, halt
and statistics
.
1.2 - 1.3
Demo program:
dog(fido).
cat(felix).
animal(X):- dog(X).
Key concepts:
-
predicate:
dog(fido)
, in section 2.2, predicate is defined as: true or false, a relation between its arguments. -
function: a expression in other language, for example: 6 + 3, first three letter of 'hello world'. Anything can be evaluated to number or string. Only be used in arithmetic expression
-
atom: a constant which is not a number, for example
fido
. Beginning with a lower case letter. Can be one of the three forms:- literal constant, e.g.: john
- string: sequence of characters enclosed in single quotes, e.g.: 'This is a tring'
- special character sequence, e.g.: +++, >=, +-
-
variable:
X
, beginning with a capital letter or a underscore -
query:
animal(fido).
-
backtrack: make Prolog provide another solution with semicolon
;
after a solution -
term: numbers, atoms, variable, compound term
-
compound terms: like record in other programming language. General form:
f(arg1, arg2, ...)
, wheref
is a functor,arg1
,arg2
, etc is *argument` -
functor: first part of a compound term, like record name, must be atom
-
arity: number of arguments in a compound term
-
argument: terms in parenthsis, like record fields, must be a (compound) term
-
list:
[arg1, arg2, ...]
, arguments in a list may be any kind -
call terms: atoms and compound terms
2.1
-
Clause: facts, or rules
-
Form of facts:
head.
-
head
must be a call term, represent the conclusion -
Form of rules:
head:- t_1,t_2,...,t_k
-
:-
: neck of a clause, read as "if" -
t1,t2,...
as a whole is called the body of the clause, specifies the conditions that must be met for the conclusion represented by the head -
Each component seperated by comma in the body is called a goal. Each goal must be a call term
-
Commas in the body are read as and
A rule is read as "head is true if t_1, t_2, ..., t_k are all true".
Or "to achieve goal head
, it's necessary to achieve subgoals
t_1, t_2, ..., t_k in turn.