You are on page 1of 66

CPT114/CPT104

Logic and Applications/


Introduction to Logic and Abstraction

Prof Madya Rosalina Abdul Salam


School of Computer Sciences, USM
rosalina@cs.usm.my
Room: 721, Tel: 04-6532486
5.2 Introduction to Prolog
The relation between Prolog and logic
Defining relations by facts
Defining relations by rules
Recursive rules
How Prolog answers questions
Declarative and procedural meaning of
programs

Reference: Bratko(2001)

CPT114/CPT104 Shahida S. (2008) 2


Win-Prolog

Programming in Logic (Prolog)


Many different compilers
 WinProlog
 Amzi
 Swi
 Others…..
For this course please use win-prolog.

CPT114/CPT104 Shahida S. (2008) 3


Win-Prolog

Website: http://www.lpa.co.uk/
Download free trial version
There are manuals available

CPT114/CPT104 Shahida S. (2008) 4


WinProlog

CPT114/CPT104 Shahida S. (2008) 5


Open new file
and start typing

CPT114/CPT104 Shahida S. (2008) 6


Load a file

CPT114/CPT104 Shahida S. (2008) 7


.pl file

CPT114/CPT104 Shahida S. (2008) 8


Using the
prompt

CPT114/CPT104 Shahida S. (2008) 9


The Relation Between Prolog and Logic
Prolog is related to mathematical logic, so its syntax
and meaning can be specified most concisely with
references to logic.

Prolog Logic
Clause form (conjunctive normal First-order predicate logic
form, quantifiers are not explicitly (predicates and quantification)
written)
Horn clauses (clauses that have at -
most one positive literal)
Procedural meaning Resolution principle for
mechanical theorem proving
Matching using “=“ Unification: substitution instance

CPT114/CPT104 Shahida S. (2008) 10


Defining Relations by Facts
Prolog: a programming language for symbolic, non-numeric
computation.
It is suitable for solving problems that involve objects and
relations between objects.
Below is a particular instance (relationship) of the parent
relation.
parent(tom, bob).
A relation: The set of all its instances.

parent(tom, X). A clause terminates


with a full stop.
Name of relation Arguments: concrete object/
constant (atom) /
general object (variable)  initial lower case
CPT114/CPT104 Shahida S. (2008) 11
Prolog System
Define a relation by stating n-tuples of objects that
satisfy the relation.
User can query the Prolog system about relations
defined in the program.
Queries/questions to the system consists of one or more
goals to be satisfied e.g.
parent(X, ann), parent(X, pat).
A sequence of goals means conjunction of the goals:
X is a parent of Ann, and
X is a parent of Pat.
An answer can be positive (satisfiable/ succeeded) or
negative (unsatisfiable/ failed).
If several answers satisfy the question then Prolog will
find all.
CPT114/CPT104 Shahida S. (2008) 12
Define a Relation for a family
parent(pam, bob).
parent(tom, bob).
parent(tom, liz).
There are 6 clauses.
parent(bob, ann). Each clause declares one
parent(bob, pat). fact about the parent
relation.
parent(pat, jim).

A particular instance of the parent relation e.g.


parent(tom, bob) is also called relationships.
Relation: the set of all instances.

CPT114/CPT104 Shahida S. (2008) 13


Example: A Family Tree
Prolog system
pam tom
Type questions via terminal:

?- parent(bob, pat).
bob liz yes Prolog
query
Prolog ?- parent(X, liz).
answer X = tom
ann pat
?- parent(Y, jim), parent(X, Y).
Answer will be the same Y = pat
although we change the X = bob
jim order of the 2
requirements as the
logical meaning are ?- parent(X, Y), parent(Y, jim).
same. Will the answer be the same?
CPT114/CPT104 Shahida S. (2008) 14
Exercise
Who are Pam’s grandchildren?
pam tom ?- parent(pam, X), parent(X, Y).
X = bob
Y = ann; Type semicolon
for more
X = bob solutions, type
bob liz
Y = pat enter to stop.

Do Bob and Liz have the same parent?


?- parent(X, bob), parent(X, liz).
ann pat X = tom
?- parent(ann, X).
no
jim ?- parent(X, jim).
X = pat
CPT114/CPT104 Shahida S. (2008) 15
Defining Relations by Rules
Types of relations:
Unary (one-place): can be used to declare simple
yes/no properties of objects.
E.g. add the following facts to the program:
female(pam).
male(jim).
Binary: defines relations between pairs of objects.
E.g. an alternative piece of program:
gender(pam, feminine).
gender(tom, masculine).

CPT114/CPT104 Shahida S. (2008) 16


Defining Relations by Rules (cont.)
Difference between facts and rules:
The clause below is a fact that is unconditionally true.
parent(tom, liz).
Rules specify things that are true if some condition is
satisfied. E.g.

child(Y, X) :- parent(X, Y).

A conclusion part/ A condition part/


head of a clause body of a clause

CPT114/CPT104 Shahida S. (2008) 17


Example
Ask whether Liz is a child of Tom:
pam tom ?- child(liz, tom).

Instantiate variable X and Y:


child(Y, X) :- parent(X, Y).
bob liz
So we get,
child(liz, tom) :- parent(tom, liz).
Prolog tries to find whether the
condition is true. Thus, initial goal:
pat child(liz, tom)
Replaced with:
parent(tom, liz)
The conclusion part is true, Prolog
jim will answer:
yes
CPT114/CPT104 Shahida S. (2008) 18
Exercise
Translate the following statements into Prolog
rules:
For all X,
X has a child if
there is some Y such that X is a parent of Y.
hasachild(X) :- parent(X, Y).

For all X and Y,


if X is a parent of Y then
X has a child.
hasachild(X) :- parent(X, Y).
CPT114/CPT104 Shahida S. (2008) 19
Another Exercise
Translate the following statements into Prolog
rules:
For all X and Y,
X is the mother of Y if
X is a parent of Y and
X is a female

mother(X, Y) :- parent(X, Y), female(X).

A comma between the conditions indicates the conjunction of


the condition. Thus both conditions must be true.

CPT114/CPT104 Shahida S. (2008) 20


Recursive Rules: Predecessor Relation
Some X is an indirect predecessor of some Z if there is
a partnership chain of people between X and Z.

X X is an indirect
X is a direct predecessor of Z predecessor of Z
parent
X Y1
parent predecessor parent predecessor

Z Y2
predecessor(X, Z) :-
predecessor(X, Z) :- parent
parent(X, Z). Z parent(X, Y1),
parent(Y1, Y2),
CPT114/CPT104 Shahida S. (2008) parent(Y2, Z). 21
How Prolog Answers Questions
Prolog tries to satisfy all goals when answering a
question.
 Demonstrate that the goal is true, assuming that the relations
in the program are true or
 Demonstrate that the goal logically follows from the facts and
rules in the program.
If the questions contain variables, Prolog has to find
the particular objects (in place of variables) for which
the goals are satisfied.
The particular instantiation of variables to these
objects is displayed to the user.
If not found, Prolog’s answer to the question will be
‘no’.

CPT114/CPT104 Shahida S. (2008) 22


Example
Prolog accepts facts and rules as a set of axioms, and
the user’s question as conjectured theorem i.e.
guessed/assumed theorem.
Then it tries to prove this theorem i.e. to demonstrate
that it can be logically derived from the axioms.
Let the axioms be:
All men are imperfect.
Socrates is a man.
A theorem that logically follows from these two
axioms:
Socrates is imperfect.
The first axiom above can be rewritten as:
For all X, if X is a man then X is imperfect.
CPT114/CPT104 Shahida S. (2008) 23
Example (cont.)
Translation into Prolog:
imperfect(X) :- man(X). %All men are imperfect
man(socrates). %Socrates is a man
?- imperfect(socrates). %Socrates is imperfect?
yes

CPT114/CPT104 Shahida S. (2008) 24


Exercise: Recall Predicate Logic

All actors are stars. axiom


Will Smith is an actor. axiom
Therefore, Will Smith is a star. theorem Translate into
Prolog

star(X) :- actor(X). %All actors are stars


actor(willSmith). %Will Smith is an actor
?- star(willSmith). % Will Smith is a star?
yes

CPT114/CPT104 Shahida S. (2008) 25


Declarative & Procedural Meaning of
Programs
Two levels of meaning of Prolog programs:
 Declarative meaning: relations defined by the
program that determines what will be the output of
the program.
 Procedural meaning: determines how this output is
obtained i.e. how the relations are actually
evaluated by the Prolog system.
Programmers can concentrate mainly on:
 declarative meaning and
 reduce/avoid being distracted by execution details.

CPT114/CPT104 Shahida S. (2008) 26


5.3 Syntax & Meaning of Prolog Programs

Data objects
Matching
Declarative meaning of Prolog programs
Procedural meaning
Order of clauses and goals

CPT114/CPT104 Shahida S. (2008) 27


Data Objects
Prolog system recognizes the type of an object
in the program by its syntactic form.
Types of Prolog objects:
 Atoms and numbers
 Variables data objects
 Structures
simple objects structures

constants variables

atoms numbers

CPT114/CPT104 Shahida S. (2008) 28


Atoms and Numbers
May have strings of the following characters:
 Upper-case letters A, B, …, Z
 Lower-case letters a, b, …, z
 Digits 0, 1, 2, …, 9
 Special characters e.g. + - * / < > : . & _ ~
Can be constructed in 3 ways:
 String of letters, digits and underscore character
starting with lower case letter
bob x_30 bob_john
 String of special characters
<==> … ::=
 String of characters enclosed in single quotes.
‘Bob’ ‘Bob_John’
Numbers include integer numbers and real numbers.
CPT114/CPT104 Shahida S. (2008) 29
Variables
Variables: strings of letters, digits and underscore
characters that start with upper-case letter or
underscore character.
X Mark2 _xy MarkList
Anonymous variable: can be used when a variable
appears in a clause once only.
hasachild(X) :- parent(X, _).
The lexical scope of variable names is one clause e.g.
the name X1 occurs in two clauses, then it signifies two
different variables.
But each occurrence of X1 within the same clause
means the same variable.

CPT114/CPT104 Shahida S. (2008) 30


Structures
Also known as structured objects that have
several components.
E.g. the date can be viewed as structure with
3 components: day, month, year.
Functor: combine the components into a single
object.
date(1, june, 2007) date(Day, june, 2007)

Arguments: can be
functor constants, variables, variable
or other structures

CPT114/CPT104 Shahida S. (2008) 31


Matching
Terms can be used to represent complex data
objects.
The most important operation on terms is
matching.
Given 2 terms, we say that they match if:
 They are identical, or
 The variables in both terms can be instantiated to
objects in such a way that after the substitution of
variables by these objects the terms become
identical.

CPT114/CPT104 Shahida S. (2008) 32


Example
The 2 terms below match:
date(D, J, 2007). date(D1, june, Y1).
One instantiation that makes both terms
identical is:
 D is instantiated to D1
 J is instantiated to june
 Y1 is instantiated to 2007
The terms below do not match: (why?)
date(D, J, 2007). date(D1, J1, 1400).

CPT114/CPT104 Shahida S. (2008) 33


Exercise
Will the following matching operations succeed
or fail? If they succeed, what are resulting
instantiations of variables?
point(A, B) = point(10, 12)
A = 10, B = 12
point(D, E) = point(X1, Y, Z)
no
plus(2, 3) = 5
no
+(2, D) = +(E, 2)

D = 2, E = 2

CPT114/CPT104 Shahida S. (2008) 34


Declarative Meaning of Prolog Programs
Consider a clause:
P :- Q, R
Declarative reading of the clause:
P is true if Q and R are true.
From Q and R follows P.
Procedural reading of the clause:
To solve problem P, first solve the subproblem Q
and then the subproblem R.
To satisfy P, first satisfy Q and then R.

CPT114/CPT104 Shahida S. (2008) 35


Declarative Meaning (cont.)
Given a program and a goal G, the declarative
meaning says:
A goal G is true (that is, satisfiable, or logically
follows from the program) if and only if:
1) there is a clause C in the program such that
2) there is a clause instance I of C such that
a) the head of I is identical to G, and
b) all the goals in the body of I are true.
A question is a list of goals separated by commas.
A list of goals is true if all the goals in the list are true
for the same instantiation of variables.
P :- Q, R. %conjunction of goals, all goals must be true
P :- Q; R. %disjunction of goals, any one has to be true

CPT114/CPT104 Shahida S. (2008) 36


Procedural Meaning
Specifies how Prolog answers questions or try
to satisfy a list of goals.
It is a procedure for executing a list of goals
with respect to a given program.

program

success/failure indicator
goal list execute
instantiation of variables

CPT114/CPT104 Shahida S. (2008) 37


Example
PROGRAM EXECUTION TRACE
big(bear). %clause1 1. Initial goal list: dark(X), big(X).
2. Scan program top to bottom, find a clause whose
big(elephant). %clause2
head matches the 1st goal dark(X). Clause7 found:
small(cat). %clause3 dark(Z) :- black(Z). Replace by instantiate body:
black(X), big(X).
brown(bear). %clause4
3. Scan to find a match with black(X). Clause5 found:
black(cat). %clause5 black(cat). This clause has no body, goal list
shrinks to: big(cat).
gray(elephant). %clause6
4. Scan for the goal big(cat). No clause found. Thus
dark(Z) :- black(Z). %clause7 backtrack to step (3) and undo the instantiation X =
%anything black is dark cat. The goal list is: black(X), big(X). Continue
scanning below clause5. Not found. Backtrack to
dark(Z) :- brown(Z). %clause8 step (2) and continue below clause7. Clause8
found. dark(Z) :- brown(Z). Replace 1st goal:
%anything brown is dark brown(X), big(X).
5. Scan to match brown(X), found brown(bear). The
goal list shrinks to big(bear).
QUESTION
6. Scan and find clause big(bear). The goal lists
?- dark(X), big(X). shrinks to empty. Successful termination: X = bear.

%who is dark and big?

CPT114/CPT104 Shahida S. (2008) 38


Order of Clauses and Goals
Danger of indefinite loop:
 Prolog enters infinite loop without any progress e.g.
p :- p. ?- p.
 Not suitable ordering of clauses and goals: Prolog will not
satisfy goal because it chooses a wrong path.
Program variations through reordering of clauses and goals: the
rule is ‘try simplest things 1st’
Combining declarative and procedural views: declaratively correct,
procedurally wrong e.g.
predecessor(X, Z) :- predecessor(X, Z).
Concentrate on declarative aspects of the problem, test resulting
program, if it fails procedurally try rearrange the clauses and goals
into a suitable order.
More techniques needed to deal with path finding, problem solving
and search.

CPT114/CPT104 Shahida S. (2008) 39


Exercise
PROGRAM Determine whether Tom
pam tom is a predecessor of Pat
%original version
pred1(X, Z) :- parent(X, Z).
using predecessor
bob liz relation. (yes, no, fail?)
pred1(X, Z) :- parent(X, Y), pred1(Y, Z).
?- pred1(tom, pat).
%version1: swap clauses of original one
pat yes
pred2(X, Z) :- parent(X, Y), pred2(Y, Z).
?- pred2(tom, pat).
pred2(X, Z) :- parent(X, Z).
jim yes
%version2: swap goals in 2nd clause of original one ?- pred3(tom, pat).
pred3(X, Z) :- parent(X, Z). yes
pred3(X, Z) :- pred3(X, Y), parent(Y, Z).
?- pred4(tom, pat).
Can’t
stack overflow
%version3: swap goals & clauses of original one find answer
pred4(X, Z) :- pred4(X, Y), parent(Y, Z). ?- pred3(liz, jim).
Infinite sequence of
pred4(X, Z) :- parent(X, Z). recursive call. stack overflow
CPT114/CPT104 Shahida S. (2008) 40
5.4 Lists, Operators, Arithmetic
Representations of lists
Operations on lists
Operator notation
Arithmetic

CPT114/CPT104 Shahida S. (2008) 41


Representation of Lists
The list is a simple data structure widely used in non-
numeric programming.
A list is a sequence of any number of items written in
Prolog as:
[nicol, squash, hafiz, badminton]
All Prolog objects are trees including lists (binary trees)
that can be either empty [ ] or non-empty consists of
items: head and tail.
.(Head, Tail)

[nicol, squash, hafiz, badminton]


head: can be any
Prolog objects
tail: must be a list
CPT114/CPT104 Shahida S. (2008) 42
Example1
The following conversation with Prolog:
?- Hobbies1 = .(tennis, .(music, [ ] ) ),
Hobbies2 = [skiing, food],
L = [ann, Hobbies1, tom, Hobbies2].

Hobbies1 = [tennis, music]


Hobbies2 = [skiing, food]
L = [ann, [tennis, music], tom, [skiing, food] ]

CPT114/CPT104 Shahida S. (2008) 43


Example2
Treat the whole tail as a single object:
L = [a, b, c]
Tail = [b, c]
L = .(a, Tail)
L = [a | Tail]
[a, b, c] = [a | [b, c] ] = [a, b | [c] ] = [a, b, c | [ ] ]
Special notation for lists:
[Item1, Item2, …] or
[Head | Tail] or
[Item1, Item2, …| Others]

CPT114/CPT104 Shahida S. (2008) 44


Operations on Lists
Membership
Concatenation
Adding an item
Deleting an item
Sublist
Permutations

CPT114/CPT104 Shahida S. (2008) 45


Membership
X is a member of L either:
1) X is the head of L, or
2) X is a member of the tail of L.
member(X, L)
Can be written in two clauses:
member(X, [X | Tail] ). %simple fact
member(X, [Head | Tail] ) :-
member(X, Tail). %rule
Example:
member(b, [a,b,c] ). %true
member(b, [a,[b,c]] ). %false, the tail is [b,c]
member([b,c],[a,[b,c]] ). %true

CPT114/CPT104 Shahida S. (2008) 46


Concatenation
Define the relation conc where L1 and L2 are
lists, L3 is their concatenation:
conc(L1, L2, L3)
Example:
conc( [a,b], [c,d], [a,b,c,d] ). %true
conc( [a,b], [c,d], [a,b,a,c,d] ). %false

?- conc( [a,b,c], [1,2,3], L).


L = [a,b,c,1,2,3]

?- conc( [a,[b,c],d], [a,[ ],b], L).


L = [a, [b,c], d, a, [ ], b]

CPT114/CPT104 Shahida S. (2008) 47


Add & Delete Item
To add an item, X to a list, L: put it in front the list as a
new head e.g.
[X | L] add(X, L, [X | L] ).
Delete an item, X from a list, L get the list L1:
del(X, L, L1).
If there are several occurrences of X in the list then del
will delete any one of them by backtracking until del
fails to delete any more item e.g.
?- del(a, [a,b,a,a], L).
L = [b,a,a];
L = [a,b,a];
L = [a,b,a];
no

CPT114/CPT104 Shahida S. (2008) 48


Sublist
The sublist relation has 2 arguments: list L and
list S such that S occurs within L as its sublist:
sublist( [c,d,e], [a,b,c,d,e,f] ). %true
sublist( [c,e], [a,b,c,d,e,f] ). %false
It can also be used to find all sublists of a given
list e.g.
?- sublist( S, [a,b,c] ).
S = [ ];
S = [a];
S = [a,b];
S = [a, b, c];
S = [ ];
S = [b];

CPT114/CPT104 Shahida S. (2008) 49


Permutations
The permutation relation with 2 arguments of 2 lists such
that one is a permutation of the other.
?- permutation( [a,b,c], P ).
P = [a,b,c];
P = [a,c,b]; X L
P = [b,a,c];
… Insert X obtain a
Example: permutation of [X | L]
?- permutation( [red,blue,green], P ).
P = [red, blue, green]; L1
P = [red, green, blue];
L1 is a permutation of L
P = [blue, red, green];
P = [blue, green, red];
P = [green, red, blue];
P = [green, blue, red];
no

CPT114/CPT104 Shahida S. (2008) 50


Operator Notation
Expressions in Mathematics such as: +
2*a + b*c
* *
 where + and * are infix operators 2 a b c
that appear between the 2 arguments, Tree representation
 2, a, b are arguments.
Prolog terms using functor (the operator with the
highest precedence (assume range: 1 to 1200) and is
the principal functor of the term:
+( *(2,a), *(b,c) )
Programmers can define their own operators e.g.
peter has pet. %the fact equivalent to…
has(peter, pet).

CPT114/CPT104 Shahida S. (2008) 51


Operator Notation (cont.)
3 groups of operator types where arguments x whose
precedence < operator, y whose precedence 
operator and f is infix:
 infix operators of 3 types:
xfx xfy yfx
 prefix operators of 2 types: Interpretation a – (b
– c) is invalid
fx fy
because prec. b – c
 postfix operators of 2 types: is not less than ‘-’
xf yf
The expression below has infix of yfx type:
a–b–c
- -
- c a -
prec. 500 a b prec. 0 prec. 0 b c
prec. 500
CPT114/CPT104 Shahida S. (2008) 52
Arithmetic
Predefined operators for basic arithmetic
operations:
 addition + subtraction - multiplication *
 division / power ** integer division //
 modula, the remainder of integer division mod
Example:
?- X is 1 + 2.
X=3
Comparing numerical values e.g.
?- 300 * 35 > 10000.
yes
CPT114/CPT104 Shahida S. (2008) 53
5.5 Using Structures: Example Program
Retrieving structured information from a
database
Doing data abstraction
Example: Travel agent

CPT114/CPT104 Shahida S. (2008) 54


Retrieving Structured Information
from a Database
A database can be represented in Prolog as a set of facts.
Example: structuring information about a family of 4 components:
name, surname, DOB, job (unemployed or working organization &
salary).
family( person(tom, fox, date(7,may,1960), works(bbc, 15200) ),
person(ann, fox, date(9, may, 1961), unemployed),
[person(pat, fox, date(5,may,1983), unemployed),
person(jim, fox, date(5,may,1983), unemployed)] ).
family
person person •

person •
tom fox date works ann fox date unemp.
[]
7 may 1960 bbc 15200 9 may 1961 pat fox date unemp. person

5 may 1983 jim fox date unemp.

5 may 1983
CPT114/CPT104 Shahida S. (2008) 55
Example: Retrieving Database
Specify objects not by content but by their
structure, leave the arguments as anonymous
variables.
Refer to all Fox family as:
family(person( _, fox, _, _), _ )
Refer all families with 3 children:
family( _, [_, _, _] )
Find all married women with at least 3 children:
?- family( person(Name, Surname,_,_ ), [_, _, _ | _] ).

CPT114/CPT104 Shahida S. (2008) 56


Data Abstraction
Data abstraction: a process of organizing
various pieces of information into natural units
(possibly hierarchically).
It is structuring the information into some
conceptually meaningful form.
Programmer makes use of information possible
without having to think about the details of how
the information is actually represented.
Select particular components using selectors
relation with 2 arguments: object that contains
the component and the component itself.
selector_relation(Object, Component_selected)
CPT114/CPT104 Shahida S. (2008) 57
Example
family( person(tom, fox, date(7,may,1960), works(bbc, 15200) ),
[person(pat, fox, date(5,may,1983), unemployed),
person(jim, fox, date(5,may,1983), unemployed)] )
Selectors for family structure:
husband(family(Husband, _, _ ), Husband).
wife(family(_, Wife, _), Wife).
children(family(_, _, ChildList), ChildList).
Generalize selector for Nth element of a list:
nthchild(N, Family, Child) :-
children(Family, ChildList),
nth_member(N, ChildList, Child). %Nth element of a list
Selectors for object person:
firstname(person(Name, _, _, _ ), Name).
surname(person(_, Surname, _, _ ), Surname).
born(person(_, _, Date, _ ), Date).

CPT114/CPT104 Shahida S. (2008) 58


Example: Travel Agent
A program that gives advice on planning air
travel to answer some questions such as:
 What days of the week is there a direct evening
flight from Ljubljana to London?
Database holds flight information:
timetable(Place1, Place2, ListOfFlights)
ListOfFlights is a list of structured items:
DepartureTime/ArrivalTime/FlightNumber/ListOfDays
E.g. of clause of the timetable relation:
timetable(london, edinburgh,
[9:40/10:50/ba4733/alldays,
19:40/20:50/ba4833/[mo,tu,we,th,fr,su] ] ).
CPT114/CPT104 Shahida S. (2008) 59
Example: Travel Agent (cont.)
Route relation:
route(Place1, Place2, Day, Route)
Route is a list of structured objects:
From/To/FlightNumber/Departure_time
Auxiliary predicates:
 There is a flight, FlightNum, between Place1 and
Place2 on the day of the week Day with specified
departure and arrival times.
flight(Place1, Place2, Day, FlightNum, DepTime, ArrTime)
 Departure time of Route is Time.
deptime(Route, Time)
 There is at least 40 minutes between Time1 and
Time2 that is sufficient for transfer between 2 flights.
transfer(Time1, Time2)

CPT114/CPT104 Shahida S. (2008) 60


Prolog Program
% A FLIGHT ROUTE PLANNER

:- op( 50, xfy, :).

% route( Place1, Place2, Day, Route):


% Route is a sequence of flights on Day, starting at Place1,
% ending at Place2

route( P1, P2, Day, [ P1 / P2 / Fnum / Deptime ] ) :- % Direct flight


flight( P1, P2, Day, Fnum, Deptime, _).

route( P1, P2, Day, [ (P1 / P3 / Fnum1 / Dep1) | RestRoute] ) :-


% Indirect connection
route( P3, P2, Day, RestRoute),
flight( P1, P3, Day, Fnum1, Dep1, Arr1),
deptime( RestRoute, Dep2), % Departure time of Route
transfer( Arr1, Dep2). % Enough time for transfer

flight( Place1, Place2, Day, Fnum, Deptime, Arrtime) :-


timetable( Place1, Place2, Flightlist),
member( Deptime / Arrtime / Fnum / Daylist , Flightlist),
flyday( Day, Daylist).

CPT114/CPT104 Shahida S. (2008) 61


Prolog Program (cont.)
% A FLIGHT ROUTE PLANNER (cont.)

flyday( Day, Daylist) :-


member( Day, Daylist).

flyday( Day, alldays) :-


member( Day, [mo,tu,we,th,fr,sa,su] ).

deptime( [ P1 / P2 / Fnum / Dep | _], Dep).

transfer( Hours1:Mins1, Hours2:Mins2) :-


60 * (Hours2 - Hours1) + Mins2 - Mins1 >= 40.

member( X, [X | L] ).

member( X, [Y | L] ) :-
member( X, L).

CPT114/CPT104 Shahida S. (2008) 62


Prolog Database
% A FLIGHT DATABASE

timetable( edinburgh, london,


[ 9:40 / 10:50 / ba4733 / alldays,
13:40 / 14:50 / ba4773 / alldays,
19:40 / 20:50 / ba4833 / [mo,tu,we,th,fr,su] ] ).

timetable( london, edinburgh,


[ 9:40 / 10:50 / ba4732 / alldays,
11:40 / 12:50 / ba4752 / alldays,
18:40 / 19:50 / ba4822 / [mo,tu,we,th,fr] ] ).

timetable( london, ljubljana,


[ 13:20 / 16:20 / jp212 / [mo,tu,we,fr,su],
16:30 / 19:30 / ba473 / [mo,we,th,sa] ] ).

timetable( london, zurich,


[ 9:10 / 11:45 / ba614 / alldays,
14:45 / 17:20 / sr805 / alldays ] ).

timetable( london, milan,


[ 8:30 / 11:20 / ba510 / alldays,
11:00 / 13:50 / az459 / alldays ] ).

timetable( ljubljana, zurich,


[ 11:30 / 12:40 / jp322 / [tu,th] ] ).
CPT114/CPT104 Shahida S. (2008) 63
Prolog Database (cont.)
% A FLIGHT DATABASE (cont.)

timetable( ljubljana, london,


[ 11:10 / 12:20 / jp211 / [mo,tu,we,fr,su],
20:30 / 21:30 / ba472 / [mo,we,th,sa] ] ).

timetable( milan, london,


[ 9:10 / 10:00 / az458 / alldays,
12:20 / 13:10 / ba511 / alldays ] ).

timetable( milan, zurich,


[ 9:25 / 10:15 / sr621 / alldays,
12:45 / 13:35 / sr623 / alldays ] ).

timetable( zurich, ljubljana,


[ 13:30 / 14:40 / jp323 / [tu,th] ] ).

timetable( zurich, london,


[ 9:00 / 9:40 / ba613 / [mo,tu,we,th,fr,sa],
16:10 / 16:55 / sr806 / [mo,tu,we,th,fr,su] ] ).

timetable( zurich, milan,


[ 7:55 / 8:45 / sr620 / alldays ] ).

CPT114/CPT104 Shahida S. (2008) 64


Operations
query3(City1,City2,City3,FN1,FN2,FN3,FN4) :-
permutation( [milan,ljubljana,zurich],[City1,City2,City3]),
flight( london, City1, tu, FN1, Dep1, Arr1),
flight( City1, City2, we, FN2, Dep2, Arr2),
flight( City2, City3, th, FN3, Dep3, Arr3),
flight( City3, london, fr, FN4, Dep4, Arr4).

conc([], L, L).

conc([X|L1],L2, [X|L3]) :-
conc(L1,L2,L3).

permutation( [], []).

permutation( L, [X | P]) :-
del( X, L, L1),
permutation( L1, P).

del( X, [X|L], L).

del( X, [Y|L], [Y|L1]) :-


del( X, L, L1).

CPT114/CPT104 Shahida S. (2008) 65


Example of Queries
What days of the week is there a direct
evening flight from Ljubljana to London?
?- flight(ljubljana, london, Day, _, DeptHour:_, _), DeptHour
>= 18.
Day = mo;
Day = we;

How can I get from Ljubljana to Edinburg on
Thursday?
?- route(ljubljana, edinburg, th, R).
R = [ljubljana/zurich/jp322/11:30, zurich/london/sr806/16:10,
london/edinburgh/ba4822/18:40]

CPT114/CPT104 Shahida S. (2008) 66

You might also like