SlideShare a Scribd company logo
1 of 49
PROLOG
WEEK 4
Concatenation- Review
 Recursive definition
 Base clause: conc the empty list to any list
produces that same list
 The recursive step says that when concatenating a
non-empty list [H|T] with a list L, the result is a list
with head H and the result of concatenating
T and L
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
How conc/3 works
 Two ways to find out:
 Use trace/0 on some examples
 Draw a search tree!
Let us consider a simple example
?- conc([a,b,c],[1,2,3], R).
Search tree example
?- conc([a,b,c],[1,2,3], R).
conc([], L, L).
conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
How conc works
 Two ways to find out:
 Use trace/0 on some examples
 Draw a search tree!
Let us consider a simple example
?- conc([a,b,c],[1,2,3], R).
Search tree example
?- conc([a,b,c],[1,2,3], R). conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R). conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R).
/ 
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R).
/ 
† R = [a|L0]
?- conc([b,c],[1,2,3],L0)
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R).
/ 
† R = [a|L0]
?- conc([b,c],[1,2,3],L0)
/ 
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R).
/ 
† R = [a|L0]
?- conc([b,c],[1,2,3],L0)
/ 
† L0=[b|L1]
?- conc([c],[1,2,3],L1)
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R).
/ 
† R = [a|L0]
?- conc([b,c],[1,2,3],L0)
/ 
† L0=[b|L1]
?- conc([c],[1,2,3],L1)
/ 
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R).
/ 
† R = [a|L0]
?- conc([b,c],[1,2,3],L0)
/ 
† L0=[b|L1]
?- conc([c],[1,2,3],L1)
/ 
† L1=[c|L2]
?- conc([],[1,2,3],L2)
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
append(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R).
/ 
† R = [a|L0]
?- conc([b,c],[1,2,3],L0)
/ 
† L0=[b|L1]
?- conc([c],[1,2,3],L1)
/ 
† L1=[c|L2]
?- conc([],[1,2,3],L2)
/ 
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R).
/ 
† R = [a|L0]
?- conc([b,c],[1,2,3],L0)
/ 
† L0=[b|L1]
?- conc([c],[1,2,3],L1)
/ 
† L1=[c|L2]
?- conc([],[1,2,3],L2)
/ 
L2=[1,2,3]
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Search tree example
?- conc([a,b,c],[1,2,3], R).
/ 
† R = [a|L0]
?- conc([b,c],[1,2,3],L0)
/ 
† L0=[b|L1]
?- conc([c],[1,2,3],L1)
/ 
† L1=[c|L2]
?- conc([],[1,2,3],L2)
/ 
L2=[1,2,3] †
L2=[1,2,3]
L1=[c|L2]=[c,1,2,3]
L0=[b|L1]=[b,c,1,2,3]
R=[a|L0]=[a,b,c,1,2,3]
conc([], L, L).
conc([H|L1], L2, [H|L3]):-
conc(L1, L2, L3).
Small exercise
Consider the following fact.
p([H|T], H, T).
Lets see what happens when we ask some simple queries.
?- p([a,b,c], X, Y).
X=a
Y=[b,c]
true
?- p([a], X, Y).
X=a
Y=[]
true
?- p([], X, Y).
false
Print a list with space
print_a_list([]).
print_a_list([H|T]):- write(H),
write(‘ ‘),
print_a_list(T).
?- print_a_list([a,b,c,d]).
a b c d
.
Add a member to a List
Code can be written as below:
add(X,L,[X|L]).
Example:
add(a,[1,2,3],L).
Delete a member from a List
Consider del(X,L,L1), deletes X from L and puts
the new list in L1.
Code can be written as below:
del(X,[X|Tail],Tail). % if X is head of the List L
del(X,[Y|Tail], [Y|Tail1]):-
del(X,Tail,Tail1).
Example:
del(1,[1,2,3],L).
Sublist
S is sublist of L if:
(1) L can be decomposed into two lists L1, L2 and
(2) L2 can be decomposed into two lists, S and
some L3
L1 L2X member(X,L)
L1 L3S
L2
L
L
[X|L2]
sublist(S,L)
Sublist
L1 L3S
L2
L
sublist(X,L)
sublist(S,L):-
conc(L1,L2,L),
conc(S,L3,L2).
Insertion
insert (X, List, BiggerList) :-
del (X, BiggerList, List).
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];
P = [b,a,c];
…
 Example:
?- permutation( [red,blue,green], P ).
P = [red, blue, green];
P = [red, green, blue];
P = [blue, red, green];
P = [blue, green, red];
P = [green, red, blue];
P = [green, blue, red];
no
X L
L1
Insert X obtain a
permutation of [X | L]
L1 is a permutation of
L
1.If the list is empty, new permutation must be
empty
permutation([],[]).
2. It the list is not empty it has a form [X|L].
permutation([X|L],P):-
permutation(L,L1),
insert(X,L1,P).
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
 Operator is force evaluation
?- X is 5/2, Y is 6//2, Z is 5 mod 2.
X = 2.5
Y = 2
Z = 1
 Comparison operator
> < >= =< =:= ==
?- born (Name, Year), Year >= 1990, Year =< 2000.
Greatest common divisor
(1) If X and Y are equal, then D is sequal to X.
(2) If X < Y, then D is equal to gcd of X and the difference Y
– X.
(3) If Y < X, then do the same as in case (2) with X and Y
interchanged.
gcd(X, X, X).
gcd(X, Y, D) :- X < Y, Y1 is Y –X, gcd(X, Y1, D).
gcd(X, Y, D) :- Y < X, gcd(Y, X, D).
Exercise For Arithmetic
Length of list – counting the item in the list.
(1) If the list is empty, then length is 0.
(2) If list not empty, then List = [Head | Tail]; then its length is equal to
1 plus the length of the tail Tail.
len([], 0).
len([_|Tail], N) :-
len(Tail, N1),
N is 1 + N1.
?- len([a,b,[c,d],e],N).
N = 4
Sum of Squares
34

b
ai
i2
sum(A,B,0) :- A > B.
sum(A,A,Res) :- Res is A*A.
sum(A,B,Res) :-
A < B, T is A + 1,
sum(T, B, R),
Res is A*A + R.
Matching vs Arithmetic Comparison
?- 1 + 2 =:= 2 + 1.
YES
?- 1 + 2 = 2 + 1.
NO
?- A + 1 = 2 + B.
A = 2
B = 1

35
Simple Examples
Matching
?- data(D,M,83) = date(D1,may,Y1) .
Matching Rules:
if S and T constants, then S & T match if they are the same object.
if S is a variable and T is anything, then they match & S is instantiated to T. if T is a var then T is
instantiated to S.
if S and T are structures, then they match if :
S and T have the same functor
all their correspondinf components match.
Example:
ver(seg(pt(X,Y),pt(X,Y1))). hor(seg(pt(X,Y),pt(X1,Y))).
?- ver(seg(pt(1,1),pt(1,2))).
yes
?- ver(seg(pt(1,1),pt(2,Y))).
no
?- hor(seg(pt(1,1),pt(2,Y))).
Y=1
?- ver(seg(pt(2,3),P)).
P=pt(2,Y)
Full PROLOG Program:
big(bear). % Clause 1
big(elephant). % Clause 2
small(cat). % Clause 3
brown(bear). % Clause 4
black(cat). % Clause 5
gray(elephant). % Clause 6
dark(Z) :- black(Z);brown(Z).
Question:
?- dark(X), big(X).
X = bear
Trace the process
1. Initial goal: dark(X),big(X)
2. dark(X) := black(X)
3. new goal: black(X),big(X)
4. found black(cat)
. check big(cat)
no clause found
backtrack to step 3
no other black
backtrack to step 2
dark(X) :- brown(X),big(X).
5. new goal: brown(X),big(X).
6. found brown(bear)
check big(bear)
both satisfied
Now Harder Example
Travel Planning
 Querying a database of flight information
timeTable(Place1, Place2, ListOfFlights).
 Form of flight item
depTime / arrTime / fltNo / days
 One day travels
?- route(Place1, Place2, Day, Route).
41
operato
r
Examples of Fact and Query
timetable(edinburgh, london,
[ 9:40 / 10:50 / ba4733 / alldays,
13:40 / 14:50 / ba4773 / alldays,
19:40 / 20:50 / ba4833 / [mo,we,fr]]).
 Note that ‘:’ should bind stronger than ‘/’.
?- route(london, paris, tu, Route)
 Form of items in the route
from / to / fltNo / depTime
42
Prolog Code
% A Flight Route Planner
:- op(50, xfy, :).
% route(Place1, Place2, Day, Route).
% Route is a sequence of flights on Day, starting at Place1 and ending at
Place2
route(P1, P2, Day, [P1 / P2 / Fnum / Deptime]) :-
flight(P1, P2, Day, Fnum, Deptime, _).
% direct flight
route(P1, P2, Day, [(P1 / P3 / Fnum1 / Dep1) | RestRoute]) :-
flight(P1, P3, Day, Fnum1, Dep1, Arr1),
route(P3, P2, Day, RestRoute),
deptime(RestRoute, Dep2),
transfer(Arr1, Dep2).
% Indirect flight - ensure enough transfer time
% optimize by propagating that constraint
43
% decoding timetable
flight(Place1, Place2, Day, Fnum, Deptime, Arrtime) :-
timetable(Place1, Place2, Flightlist),
member(Deptime / Arrtime / Fnum / Daylist, Flightlist),
flyday(Day, Daylist).
flyday(Day, Daylist) :- member(Day, Daylist).
flyday(Day, alldays) :- member(Day,
[mo,tu,we,th,fr,sa,su]).
deptime([( _ / _ / _ / Dep) | _], Dep).
transfer(Hours1:Mins1, Hours2:Mins2) :-
60 * (Hours2 - Hours1) + Mins2 - Mins1 >= 40.
% must have 40 min gap
44
% 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]]).
45
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]]).
timetable(ljubljana, london,
[ 11:10 / 12:20 / jp211 / [mo,tu,we,fr,su],
20:30 / 21:30 / ba472 / [mo,we,th,sa]]).
46
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]).
47
Queries
 What days of the week is there is a direct
evening flight from Ljubljana to London?
?- flight(ljubljana, london, Day, _,
DepHour:_,_), DepHour >= 18.
 How can I get from Ljubljana to London on
Thursday?
?- route(ljubljana, london, th, R).
 Queries can result in infinite loops or stack
overflow on Prolog.
48
SWI-Prolog vs XSB
XSB: table route/4.
 How can I get from Ljubljana to Edinburgh
on Thursday?
?- route(ljubljana, edinburgh, th, R).
SWI-Prolog: Out of local stack
XSB: [ ljubljana / zurich / jp322 / 11 : 30,
zurich / london / sr806 / 16 : 10,
london / edinburgh / ba4822 / 18 :
40];
49

More Related Content

What's hot

Prerequisite for metric space
Prerequisite for metric spacePrerequisite for metric space
Prerequisite for metric spaceROHAN GAIKWAD
 
Unit 2 analysis of continuous time signals-mcq questions
Unit 2   analysis of continuous time signals-mcq questionsUnit 2   analysis of continuous time signals-mcq questions
Unit 2 analysis of continuous time signals-mcq questionsDr.SHANTHI K.G
 
Convergence methods for approximated reciprocal and reciprocal-square-root
Convergence methods for approximated reciprocal and reciprocal-square-rootConvergence methods for approximated reciprocal and reciprocal-square-root
Convergence methods for approximated reciprocal and reciprocal-square-rootKeigo Nitadori
 
RECURRENCE EQUATIONS & ANALYZING THEM
RECURRENCE EQUATIONS & ANALYZING THEMRECURRENCE EQUATIONS & ANALYZING THEM
RECURRENCE EQUATIONS & ANALYZING THEMAlpana Ingale
 
Lesson 7: Vector-valued functions
Lesson 7: Vector-valued functionsLesson 7: Vector-valued functions
Lesson 7: Vector-valued functionsMatthew Leingang
 
Bellman ford
Bellman fordBellman ford
Bellman fordKiran K
 
Graph for Coulomb damped oscillation
Graph for Coulomb damped oscillationGraph for Coulomb damped oscillation
Graph for Coulomb damped oscillationphanhung20
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree methodRajendran
 
Matrix of linear transformation
Matrix of linear transformationMatrix of linear transformation
Matrix of linear transformationbeenishbeenish
 
On Twisted Paraproducts and some other Multilinear Singular Integrals
On Twisted Paraproducts and some other Multilinear Singular IntegralsOn Twisted Paraproducts and some other Multilinear Singular Integrals
On Twisted Paraproducts and some other Multilinear Singular IntegralsVjekoslavKovac1
 
Variations on the method of Coleman-Chabauty
Variations on the method of Coleman-ChabautyVariations on the method of Coleman-Chabauty
Variations on the method of Coleman-Chabautymmasdeu
 
Longest common subsequence
Longest common subsequenceLongest common subsequence
Longest common subsequenceKiran K
 
A T(1)-type theorem for entangled multilinear Calderon-Zygmund operators
A T(1)-type theorem for entangled multilinear Calderon-Zygmund operatorsA T(1)-type theorem for entangled multilinear Calderon-Zygmund operators
A T(1)-type theorem for entangled multilinear Calderon-Zygmund operatorsVjekoslavKovac1
 
Topic: Fourier Series ( Periodic Function to change of interval)
Topic: Fourier Series ( Periodic Function to  change of interval)Topic: Fourier Series ( Periodic Function to  change of interval)
Topic: Fourier Series ( Periodic Function to change of interval)Abhishek Choksi
 
Master method theorem
Master method theoremMaster method theorem
Master method theoremRajendran
 
Single source shortes path in dag
Single source shortes path in dagSingle source shortes path in dag
Single source shortes path in dagKiran K
 
Quantitative norm convergence of some ergodic averages
Quantitative norm convergence of some ergodic averagesQuantitative norm convergence of some ergodic averages
Quantitative norm convergence of some ergodic averagesVjekoslavKovac1
 

What's hot (20)

Prerequisite for metric space
Prerequisite for metric spacePrerequisite for metric space
Prerequisite for metric space
 
Recurrences
RecurrencesRecurrences
Recurrences
 
Ece4510 notes03
Ece4510 notes03Ece4510 notes03
Ece4510 notes03
 
Unit 2 analysis of continuous time signals-mcq questions
Unit 2   analysis of continuous time signals-mcq questionsUnit 2   analysis of continuous time signals-mcq questions
Unit 2 analysis of continuous time signals-mcq questions
 
Convergence methods for approximated reciprocal and reciprocal-square-root
Convergence methods for approximated reciprocal and reciprocal-square-rootConvergence methods for approximated reciprocal and reciprocal-square-root
Convergence methods for approximated reciprocal and reciprocal-square-root
 
RECURRENCE EQUATIONS & ANALYZING THEM
RECURRENCE EQUATIONS & ANALYZING THEMRECURRENCE EQUATIONS & ANALYZING THEM
RECURRENCE EQUATIONS & ANALYZING THEM
 
Lesson 7: Vector-valued functions
Lesson 7: Vector-valued functionsLesson 7: Vector-valued functions
Lesson 7: Vector-valued functions
 
Bellman ford
Bellman fordBellman ford
Bellman ford
 
Graph for Coulomb damped oscillation
Graph for Coulomb damped oscillationGraph for Coulomb damped oscillation
Graph for Coulomb damped oscillation
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Matrix of linear transformation
Matrix of linear transformationMatrix of linear transformation
Matrix of linear transformation
 
On Twisted Paraproducts and some other Multilinear Singular Integrals
On Twisted Paraproducts and some other Multilinear Singular IntegralsOn Twisted Paraproducts and some other Multilinear Singular Integrals
On Twisted Paraproducts and some other Multilinear Singular Integrals
 
Math
MathMath
Math
 
Variations on the method of Coleman-Chabauty
Variations on the method of Coleman-ChabautyVariations on the method of Coleman-Chabauty
Variations on the method of Coleman-Chabauty
 
Longest common subsequence
Longest common subsequenceLongest common subsequence
Longest common subsequence
 
A T(1)-type theorem for entangled multilinear Calderon-Zygmund operators
A T(1)-type theorem for entangled multilinear Calderon-Zygmund operatorsA T(1)-type theorem for entangled multilinear Calderon-Zygmund operators
A T(1)-type theorem for entangled multilinear Calderon-Zygmund operators
 
Topic: Fourier Series ( Periodic Function to change of interval)
Topic: Fourier Series ( Periodic Function to  change of interval)Topic: Fourier Series ( Periodic Function to  change of interval)
Topic: Fourier Series ( Periodic Function to change of interval)
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Single source shortes path in dag
Single source shortes path in dagSingle source shortes path in dag
Single source shortes path in dag
 
Quantitative norm convergence of some ergodic averages
Quantitative norm convergence of some ergodic averagesQuantitative norm convergence of some ergodic averages
Quantitative norm convergence of some ergodic averages
 

Viewers also liked

Masc legislative action day 20120215
Masc legislative action day 20120215Masc legislative action day 20120215
Masc legislative action day 20120215SCRetirement
 
Bleedblue
BleedblueBleedblue
Bleedbluelnvswm
 
Construction facts of the EURO 2016 stadiums
Construction facts of the EURO 2016 stadiumsConstruction facts of the EURO 2016 stadiums
Construction facts of the EURO 2016 stadiumsFINALCAD
 

Viewers also liked (6)

Resume 2012
Resume 2012Resume 2012
Resume 2012
 
Tallers
TallersTallers
Tallers
 
Masc legislative action day 20120215
Masc legislative action day 20120215Masc legislative action day 20120215
Masc legislative action day 20120215
 
Uma the company story
Uma   the company storyUma   the company story
Uma the company story
 
Bleedblue
BleedblueBleedblue
Bleedblue
 
Construction facts of the EURO 2016 stadiums
Construction facts of the EURO 2016 stadiumsConstruction facts of the EURO 2016 stadiums
Construction facts of the EURO 2016 stadiums
 

Similar to Week 4

Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
 
TENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONTENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONAndré Panisson
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdfSrinivasaReddyPolamR
 
140106 isaim-okayama
140106 isaim-okayama140106 isaim-okayama
140106 isaim-okayamagumitaro2012
 
Existence of Solutions of Fractional Neutral Integrodifferential Equations wi...
Existence of Solutions of Fractional Neutral Integrodifferential Equations wi...Existence of Solutions of Fractional Neutral Integrodifferential Equations wi...
Existence of Solutions of Fractional Neutral Integrodifferential Equations wi...inventionjournals
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqPradeep Bisht
 
Redundancy in robot manipulators and multi robot systems
Redundancy in robot manipulators and multi robot systemsRedundancy in robot manipulators and multi robot systems
Redundancy in robot manipulators and multi robot systemsSpringer
 
Fixed point result in menger space with ea property
Fixed point result in menger space with ea propertyFixed point result in menger space with ea property
Fixed point result in menger space with ea propertyAlexander Decker
 
Low rank tensor approximation of probability density and characteristic funct...
Low rank tensor approximation of probability density and characteristic funct...Low rank tensor approximation of probability density and characteristic funct...
Low rank tensor approximation of probability density and characteristic funct...Alexander Litvinenko
 
Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889anhsaobang1289
 
DSP_Fourier_160301.pptx
DSP_Fourier_160301.pptxDSP_Fourier_160301.pptx
DSP_Fourier_160301.pptxHamedNassar5
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingEelco Visser
 
Estimating structured vector autoregressive models
Estimating structured vector autoregressive modelsEstimating structured vector autoregressive models
Estimating structured vector autoregressive modelsAkira Tanimoto
 
Low-rank tensor approximation (Introduction)
Low-rank tensor approximation (Introduction)Low-rank tensor approximation (Introduction)
Low-rank tensor approximation (Introduction)Alexander Litvinenko
 

Similar to Week 4 (20)

Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
 
A05920109
A05920109A05920109
A05920109
 
TENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHONTENSOR DECOMPOSITION WITH PYTHON
TENSOR DECOMPOSITION WITH PYTHON
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdf
 
02_AJMS_297_21.pdf
02_AJMS_297_21.pdf02_AJMS_297_21.pdf
02_AJMS_297_21.pdf
 
140106 isaim-okayama
140106 isaim-okayama140106 isaim-okayama
140106 isaim-okayama
 
Existence of Solutions of Fractional Neutral Integrodifferential Equations wi...
Existence of Solutions of Fractional Neutral Integrodifferential Equations wi...Existence of Solutions of Fractional Neutral Integrodifferential Equations wi...
Existence of Solutions of Fractional Neutral Integrodifferential Equations wi...
 
Laplace_1.ppt
Laplace_1.pptLaplace_1.ppt
Laplace_1.ppt
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
 
Redundancy in robot manipulators and multi robot systems
Redundancy in robot manipulators and multi robot systemsRedundancy in robot manipulators and multi robot systems
Redundancy in robot manipulators and multi robot systems
 
Lecture5
Lecture5Lecture5
Lecture5
 
Fixed point result in menger space with ea property
Fixed point result in menger space with ea propertyFixed point result in menger space with ea property
Fixed point result in menger space with ea property
 
Low rank tensor approximation of probability density and characteristic funct...
Low rank tensor approximation of probability density and characteristic funct...Low rank tensor approximation of probability density and characteristic funct...
Low rank tensor approximation of probability density and characteristic funct...
 
Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889Bai tap-prolog-da-tap-hop-9889
Bai tap-prolog-da-tap-hop-9889
 
Functions
FunctionsFunctions
Functions
 
DSP_Fourier_160301.pptx
DSP_Fourier_160301.pptxDSP_Fourier_160301.pptx
DSP_Fourier_160301.pptx
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
 
Estimating structured vector autoregressive models
Estimating structured vector autoregressive modelsEstimating structured vector autoregressive models
Estimating structured vector autoregressive models
 
new math seminar paper
new math seminar papernew math seminar paper
new math seminar paper
 
Low-rank tensor approximation (Introduction)
Low-rank tensor approximation (Introduction)Low-rank tensor approximation (Introduction)
Low-rank tensor approximation (Introduction)
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaWSO2
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseWSO2
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....rightmanforbloodline
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 

Week 4

  • 2. Concatenation- Review  Recursive definition  Base clause: conc the empty list to any list produces that same list  The recursive step says that when concatenating a non-empty list [H|T] with a list L, the result is a list with head H and the result of concatenating T and L conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 3. How conc/3 works  Two ways to find out:  Use trace/0 on some examples  Draw a search tree! Let us consider a simple example ?- conc([a,b,c],[1,2,3], R).
  • 4. Search tree example ?- conc([a,b,c],[1,2,3], R). conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 5. How conc works  Two ways to find out:  Use trace/0 on some examples  Draw a search tree! Let us consider a simple example ?- conc([a,b,c],[1,2,3], R).
  • 6. Search tree example ?- conc([a,b,c],[1,2,3], R). conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 7. Search tree example ?- conc([a,b,c],[1,2,3], R). conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 8. Search tree example ?- conc([a,b,c],[1,2,3], R). / conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 9. Search tree example ?- conc([a,b,c],[1,2,3], R). / † R = [a|L0] ?- conc([b,c],[1,2,3],L0) conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 10. Search tree example ?- conc([a,b,c],[1,2,3], R). / † R = [a|L0] ?- conc([b,c],[1,2,3],L0) / conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 11. Search tree example ?- conc([a,b,c],[1,2,3], R). / † R = [a|L0] ?- conc([b,c],[1,2,3],L0) / † L0=[b|L1] ?- conc([c],[1,2,3],L1) conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 12. Search tree example ?- conc([a,b,c],[1,2,3], R). / † R = [a|L0] ?- conc([b,c],[1,2,3],L0) / † L0=[b|L1] ?- conc([c],[1,2,3],L1) / conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 13. Search tree example ?- conc([a,b,c],[1,2,3], R). / † R = [a|L0] ?- conc([b,c],[1,2,3],L0) / † L0=[b|L1] ?- conc([c],[1,2,3],L1) / † L1=[c|L2] ?- conc([],[1,2,3],L2) conc([], L, L). conc([H|L1], L2, [H|L3]):- append(L1, L2, L3).
  • 14. Search tree example ?- conc([a,b,c],[1,2,3], R). / † R = [a|L0] ?- conc([b,c],[1,2,3],L0) / † L0=[b|L1] ?- conc([c],[1,2,3],L1) / † L1=[c|L2] ?- conc([],[1,2,3],L2) / conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 15. Search tree example ?- conc([a,b,c],[1,2,3], R). / † R = [a|L0] ?- conc([b,c],[1,2,3],L0) / † L0=[b|L1] ?- conc([c],[1,2,3],L1) / † L1=[c|L2] ?- conc([],[1,2,3],L2) / L2=[1,2,3] conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 16. Search tree example ?- conc([a,b,c],[1,2,3], R). / † R = [a|L0] ?- conc([b,c],[1,2,3],L0) / † L0=[b|L1] ?- conc([c],[1,2,3],L1) / † L1=[c|L2] ?- conc([],[1,2,3],L2) / L2=[1,2,3] † L2=[1,2,3] L1=[c|L2]=[c,1,2,3] L0=[b|L1]=[b,c,1,2,3] R=[a|L0]=[a,b,c,1,2,3] conc([], L, L). conc([H|L1], L2, [H|L3]):- conc(L1, L2, L3).
  • 17. Small exercise Consider the following fact. p([H|T], H, T). Lets see what happens when we ask some simple queries. ?- p([a,b,c], X, Y). X=a Y=[b,c] true ?- p([a], X, Y). X=a Y=[] true ?- p([], X, Y). false
  • 18. Print a list with space print_a_list([]). print_a_list([H|T]):- write(H), write(‘ ‘), print_a_list(T). ?- print_a_list([a,b,c,d]). a b c d .
  • 19.
  • 20. Add a member to a List Code can be written as below: add(X,L,[X|L]). Example: add(a,[1,2,3],L).
  • 21. Delete a member from a List Consider del(X,L,L1), deletes X from L and puts the new list in L1. Code can be written as below: del(X,[X|Tail],Tail). % if X is head of the List L del(X,[Y|Tail], [Y|Tail1]):- del(X,Tail,Tail1). Example: del(1,[1,2,3],L).
  • 22. Sublist S is sublist of L if: (1) L can be decomposed into two lists L1, L2 and (2) L2 can be decomposed into two lists, S and some L3 L1 L2X member(X,L) L1 L3S L2 L L [X|L2] sublist(S,L)
  • 24. Insertion insert (X, List, BiggerList) :- del (X, BiggerList, List).
  • 25. 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]; P = [b,a,c]; …  Example: ?- permutation( [red,blue,green], P ). P = [red, blue, green]; P = [red, green, blue]; P = [blue, red, green]; P = [blue, green, red]; P = [green, red, blue]; P = [green, blue, red]; no X L L1 Insert X obtain a permutation of [X | L] L1 is a permutation of L
  • 26. 1.If the list is empty, new permutation must be empty permutation([],[]). 2. It the list is not empty it has a form [X|L]. permutation([X|L],P):- permutation(L,L1), insert(X,L1,P).
  • 28.  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
  • 29. CPT114  Operator is force evaluation ?- X is 5/2, Y is 6//2, Z is 5 mod 2. X = 2.5 Y = 2 Z = 1  Comparison operator > < >= =< =:= == ?- born (Name, Year), Year >= 1990, Year =< 2000.
  • 30. Greatest common divisor (1) If X and Y are equal, then D is sequal to X. (2) If X < Y, then D is equal to gcd of X and the difference Y – X. (3) If Y < X, then do the same as in case (2) with X and Y interchanged. gcd(X, X, X). gcd(X, Y, D) :- X < Y, Y1 is Y –X, gcd(X, Y1, D). gcd(X, Y, D) :- Y < X, gcd(Y, X, D). Exercise For Arithmetic
  • 31. Length of list – counting the item in the list. (1) If the list is empty, then length is 0. (2) If list not empty, then List = [Head | Tail]; then its length is equal to 1 plus the length of the tail Tail. len([], 0). len([_|Tail], N) :- len(Tail, N1), N is 1 + N1. ?- len([a,b,[c,d],e],N). N = 4
  • 32.
  • 33.
  • 34. Sum of Squares 34  b ai i2 sum(A,B,0) :- A > B. sum(A,A,Res) :- Res is A*A. sum(A,B,Res) :- A < B, T is A + 1, sum(T, B, R), Res is A*A + R.
  • 35. Matching vs Arithmetic Comparison ?- 1 + 2 =:= 2 + 1. YES ?- 1 + 2 = 2 + 1. NO ?- A + 1 = 2 + B. A = 2 B = 1  35
  • 37. Matching ?- data(D,M,83) = date(D1,may,Y1) . Matching Rules: if S and T constants, then S & T match if they are the same object. if S is a variable and T is anything, then they match & S is instantiated to T. if T is a var then T is instantiated to S. if S and T are structures, then they match if : S and T have the same functor all their correspondinf components match. Example: ver(seg(pt(X,Y),pt(X,Y1))). hor(seg(pt(X,Y),pt(X1,Y))). ?- ver(seg(pt(1,1),pt(1,2))). yes ?- ver(seg(pt(1,1),pt(2,Y))). no ?- hor(seg(pt(1,1),pt(2,Y))). Y=1 ?- ver(seg(pt(2,3),P)). P=pt(2,Y)
  • 38. Full PROLOG Program: big(bear). % Clause 1 big(elephant). % Clause 2 small(cat). % Clause 3 brown(bear). % Clause 4 black(cat). % Clause 5 gray(elephant). % Clause 6 dark(Z) :- black(Z);brown(Z). Question: ?- dark(X), big(X). X = bear
  • 39. Trace the process 1. Initial goal: dark(X),big(X) 2. dark(X) := black(X) 3. new goal: black(X),big(X) 4. found black(cat) . check big(cat) no clause found backtrack to step 3 no other black backtrack to step 2 dark(X) :- brown(X),big(X). 5. new goal: brown(X),big(X). 6. found brown(bear) check big(bear) both satisfied
  • 41. Travel Planning  Querying a database of flight information timeTable(Place1, Place2, ListOfFlights).  Form of flight item depTime / arrTime / fltNo / days  One day travels ?- route(Place1, Place2, Day, Route). 41 operato r
  • 42. Examples of Fact and Query timetable(edinburgh, london, [ 9:40 / 10:50 / ba4733 / alldays, 13:40 / 14:50 / ba4773 / alldays, 19:40 / 20:50 / ba4833 / [mo,we,fr]]).  Note that ‘:’ should bind stronger than ‘/’. ?- route(london, paris, tu, Route)  Form of items in the route from / to / fltNo / depTime 42
  • 43. Prolog Code % A Flight Route Planner :- op(50, xfy, :). % route(Place1, Place2, Day, Route). % Route is a sequence of flights on Day, starting at Place1 and ending at Place2 route(P1, P2, Day, [P1 / P2 / Fnum / Deptime]) :- flight(P1, P2, Day, Fnum, Deptime, _). % direct flight route(P1, P2, Day, [(P1 / P3 / Fnum1 / Dep1) | RestRoute]) :- flight(P1, P3, Day, Fnum1, Dep1, Arr1), route(P3, P2, Day, RestRoute), deptime(RestRoute, Dep2), transfer(Arr1, Dep2). % Indirect flight - ensure enough transfer time % optimize by propagating that constraint 43
  • 44. % decoding timetable flight(Place1, Place2, Day, Fnum, Deptime, Arrtime) :- timetable(Place1, Place2, Flightlist), member(Deptime / Arrtime / Fnum / Daylist, Flightlist), flyday(Day, Daylist). flyday(Day, Daylist) :- member(Day, Daylist). flyday(Day, alldays) :- member(Day, [mo,tu,we,th,fr,sa,su]). deptime([( _ / _ / _ / Dep) | _], Dep). transfer(Hours1:Mins1, Hours2:Mins2) :- 60 * (Hours2 - Hours1) + Mins2 - Mins1 >= 40. % must have 40 min gap 44
  • 45. % 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]]). 45
  • 46. 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]]). timetable(ljubljana, london, [ 11:10 / 12:20 / jp211 / [mo,tu,we,fr,su], 20:30 / 21:30 / ba472 / [mo,we,th,sa]]). 46
  • 47. 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]). 47
  • 48. Queries  What days of the week is there is a direct evening flight from Ljubljana to London? ?- flight(ljubljana, london, Day, _, DepHour:_,_), DepHour >= 18.  How can I get from Ljubljana to London on Thursday? ?- route(ljubljana, london, th, R).  Queries can result in infinite loops or stack overflow on Prolog. 48
  • 49. SWI-Prolog vs XSB XSB: table route/4.  How can I get from Ljubljana to Edinburgh on Thursday? ?- route(ljubljana, edinburgh, th, R). SWI-Prolog: Out of local stack XSB: [ ljubljana / zurich / jp322 / 11 : 30, zurich / london / sr806 / 16 : 10, london / edinburgh / ba4822 / 18 : 40]; 49

Editor's Notes

  1. Numeric comparison operators: <, >, =<, >=, =:=, =\= To solve a numeric comparison goal, Prolog evaluates both sides and compares the results numerically So both sides must be fully instantiated ?- A + 1 =:= 2 + B. ERROR: =:=/2: Arguments are not sufficiently instantiated
  2. captures logic and database like querying for more sophisticated control for optimal routing problem: need additional constructs
  3. enable hr:min:sec
  4. member built-in in SWI-Prolog but requires explicit definition in XSB.