1. CSE240 – Introduction to
Programming Languages
Lecture 25:
Programming with Prolog IV
Javier Gonzalez-Sanchez
javiergs@asu.edu
javiergs.engineering.asu.edu
Office Hours: By appointment
2. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 2
Announcement
• Homework 6 due Nov 29.
• Quiz 9 due Nov 29.
4. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 4
Arithmetic Queries
?- X is 3 + 5.
X=8
?- X is 3 mod 2.
X=1
?- X is 3 mod 2 - 1 * 5 / 9.
X=0.4444444444444444
?- X is 5+4, Y is 5-4.
X=9
Y=1
?- X is 5*4, Y is 2^3.
X=20
Y=8
5. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 5
Arithmetic Queries
?- X is 234556^100.
X = 1058411813164889882981775915184...
?- X is 5/3.
X=1.66666667
?- X is sqrt(3),Y is 3^0.5.
X=Y
Y=1.7320508075688772
?- X is 8 mod 3.
X=2
?- Y is 10^3 * (1+1) + 3.
Y=2003
7. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 7
Test Yourselves
• X is 5 /3, X = 1.
false
• X is 5 /3; X = 1.
X = 1.6666666667
X = 1
• doSomething(A,B,P) :- P is A + B.
?-doSomething(3,2,P).
?-doSomething(3,2,10).
8. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 8
Recursion
% this is fact
factorial(0, 1).
% this is a rule
% the factorial of F is N*F1
% if N>0 and
% N1 is N-1 and
% the factorial of N1 is F1
factorial(N, F) :-
N>0,
N1 is N - 1,
factorial(N1, F1),
F is N * F1.
?- factorial (3, W).
W=6
1. factorial(3, W)
apply rule 2
2. 3>0, N1 is 3-1, factorial (N1, F1), F is 3 *F1
solve the individual parts
true, 2 is 3-1, factorial (2, F1), F is 3*F1
apply rule 2 again
3. 2>0, N2 is 2-1, factorial (N2, F2), F1 is 2 * F2
solve the individual parts
true, 1 is 2-1, factorial (1, F1), F1 is 2*F2
apply rule 2 again
4. 1>0, N3 is 1-1, factorial (N3, F3), F2 is 2 * F3
solve the individual parts
true, 0 is 1-1, factorial (0, F3), F2 is 1*F3
apply rule 1
5. factorial (0, 1)
F3 is 1
6. Go back, replace F3 to get F2, then F2 to get F1,
then F1 to get F.
10. Javier Gonzalez-Sanchez | CSE 240 | Fall 2017 | 10
Test Yourselves
fib(0, 0).
fib(1, 1).
fib(X, Y) :- X > 1,
X2 is X – 2, fib(X2, Y2),
X1 is X – 1, fib(X1, Y1),
Y is Y1 + Y2.
12. CSE240 – Introduction to Programming Languages
Javier Gonzalez-Sanchez
javiergs@asu.edu
Fall 2017
Disclaimer. These slides can only be used as study material for the class CSE240 at ASU. They cannot be distributed or used for another purpose.