- Computer programming in Prolog consists of:
- specifying some facts about objects and their relationships
- defining some rules about objects and their relationships
- asking questions about objects and their relationships
- Facts
likes(john, mary). /* John likes Mary */
likes(mary, john). /* not necessarily the case */
valuable(gold). /* Gold is valuable */
female(jane). /* Jane is a female */
owns(jane, gold). /* Jane owns gold */
father(john, mary). /* John is the father of Mary */
gives(john, book, mary) /* Johns gives the book to Mary */
play(john, mary, football).
play(jane, jim, badminton).
king(john, france).
likes(joe,fish).
likes(joe,mary).
likes(mary,book).
likes(john,book).
likes(john,france).
human(socrates).
human(aristotle).
athenian(socrates).
- Questions and variables.
?-likes(joe,money).
no
?-likes(mary,joe).
no
?-likes(mary,book).
yes
?-athenian(socrates).
yes
?-athenian(aristotle).
no
?-likes(john,X).
X=mary;
X=book
?-likes(john,WhatdoesJohnLike).
WhatdoesJohnLike=mary
A CONJUNCTION: ','
?-likes(mary,X), like(john,X).
- Rules
likes(john,X) :- likes(X,book).
likes(john,X) :- likes(X, football),
likes(X, badminton).
sister_of(X,Y) :-
female(X),
parents(X, M, F),
parents(Y, M, F).
may_steal(P,T) :- thief(P), likes(P,T).
- Math in Prolog
test(X,Y) :- Y is X - 10.
cube(X,Y) :- Y is X*X*X.
volume(SphereRadius, V) :- cube(SphereRadius, C),
V is (4/3) * 3.14159 * C.
/*
?- test(22,Y).
Y = 12
Yes
?- volume(10,X).
X = 4188.79
Yes
?- cube(10,X).
X = 1000
Yes
*/
- Lists in Prolog
first([Head|_], Head). /* The underscore, '_', is an anonymous variable in Prolog */
/* This means that you don't care about this variable's value */
rest([_|RestofList], RestofList).
parts([Head|Tail], Head, Tail).
/*
?- first([a,c,s,d,e], X).
X = a
Yes
?- rest([a,c,s,d,e], X).
X = [c, s, d, e]
Yes
?- parts([a,c,s,d,e], X,Y).
X = a
Y = [c, s, d, e]
Yes
*/
- Defining a predicate to test membership in a list
member(X, [X|_]).
member(X, [_|RestofList]) :- member(X, RestofList).
/*
member(X, [X|_]). This means "X is a member of the list with X as the first member.
member(X, [_|RestofList) :- member(X, RestofList).
This is checking recursively whether X is a member of the RestofList, if X was not the first element.
?- consult(test).
% test compiled 0.01 sec, 92 bytes
Yes
?- member(a,[b,e,r,a,c,g]).
Yes
?- member(a,[b,e,r,c,g]).
No
*/
- Starting Prolog
- swiprolog starts SWI Prolog
- ?-consult(first). Loads first.pl
- or you can put single quotes around the name of the file to load, such as ?-consult('first.pl').
- halt. exits SWI Prolog.