400

# CSE240 Lecture 26

Introduction to Programming Languages
Recursion in Prolog
(202204)

January 26, 2017

## Transcript

1. jgs
CSE 240
Introduction to Programming Languages
Lecture 26: Recursion in Prolog
Dr. Javier Gonzalez-Sanchez
[email protected]
javiergs.engineering.asu.edu | javiergs.com
PERALTA 230U
Office Hours: By appointment

2. jgs
Previously

3. Javier Gonzalez-Sanchez | CSE240 | Spring 2020 | 3
jgs
Arithmetic Queries
?- X is 10+5.
X = 15
?- 6 is 10+5.
false
?- 15 is 10+5.
true
?- 10+5 is X.
Error: Arguments are not sufficiently instantiated
?- 10+5 is 10+5.
false

4. Javier Gonzalez-Sanchez | CSE240 | Spring 2020 | 4
jgs
Arithmetic Queries
§ X is 5 /3, X = 1.
false
§ X is 5 /3, Y = 1.
X=1.666666667,
Y=1
§ X is 5 /3; X = 1.
X = 1.6666666667
X = 1

5. jgs
Rules and Recursion

6. Javier Gonzalez-Sanchez | CSE240 | Spring 2020 | 6
jgs
Rules as functions
§ doSomething(A,B,P) :- P is A + B.
?-doSomething(3,2,P).
?-doSomething(3,2,10).

7. Javier Gonzalez-Sanchez | CSE240 | Spring 2020 | 7
jgs
Recursion | Factorial
% 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.

8. Javier Gonzalez-Sanchez | CSE240 | Spring 2020 | 8
jgs
Recursion | Factorial

9. Javier Gonzalez-Sanchez | CSE240 | Spring 2020 | 9
jgs
Recursion | Fibonacci
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.

10. Javier Gonzalez-Sanchez | CSE240 | Spring 2020 | 10
jgs
Recursion | Fibonacci

11. jgs
Test Yourselves
C/C++

12. Javier Gonzalez-Sanchez | CSE240 | Spring 2020 | 12
jgs
Test Yourselves
§ A recursive function rec is defined as follows
Write a set of rules in Prolog to define the solution to this function.
ï
î
ï
í
ì
³
-
-
+
-
=
£
=
3
)
3
(
*
)
2
(
)
1
(
2
1
1
0
)
(
n
n
rec
n
rec
n
rec
n
n
n
rec

13. jgs
CSE 240 Introduction to Programming Languages
Javier Gonzalez-Sanchez, Ph.D.
[email protected]
Fall 2021
Copyright. These slides can only be used as study material for the class CSE240 at Arizona State University.
They cannot be distributed or used for another purpose.