7 Prolog3 Arithmetic
7 Prolog3 Arithmetic
Programming Paradigms
1
• Course overview
• Introduction to programming
paradigms
• Review: The object-oriented
Topics paradigm in Java
• Imperative and concurrent
programming paradigm: Go.
• Logic paradigm: Prolog.
• Functional paradigm: Scheme.
• Quiz 3 is available ends on
Saturday Feb 13th ?
Announcement • Q1 and Q2 feedback is released
• TA(Harman)
• Thursday Feb 12 (4:00 -5:20 pm)
live Tutorial session for
comprehensive assg_part1 Go
Announcement Concurrent
• (TA: Bamdad)
• Comprehensive
assigenemnt_part1 Go -> due date
extended to Friday Feb 26th
Announcement • TA (Bamdad) will help and mark
it
• Assignment 1 (GO) will be posted
Announcement tonight -> Due date March 1st
• Recorded lecture?
Announcement • Go concurrent visualize execution
Arithmetic Expressions and I/O
• Arithmetic Expressions
– Built-in operators
– Unification with numbers
– Recursive calculations
– Generator
Numbers in Prolog
• Prolog recognizes numbers
– integers and floating point
• Number constants
5 1.75 0 1.345e-10 -27 -3.4 42
• Rules about arithmetic expressions use
– number constants
– arithmetic operators
– arithmetic variables
Arithmetic Expressions
• Prolog supports common operators as built-ins
including
X+Y
X-Y
X*Y
X/Y
X // Y %integer division
X mod Y
• Mathematical functions, e.g.,
abs(X)
ln(X)
sqrt(X)
Evaluating Arithmetic Expressions
• Comparisons
X =:= Y % X equals Y
X =\= Y % X not equals Y
X < Y
X =< Y
X > Y
X >= Y
• The operators are applied after calculations,
e.g.,
?- 1+2 =:= 2+1.
true.
Example: Min Predicate
min(X,Y,X) :- X<Y.
min(X,Y,Y) :- X>=Y.
• What queries can we ask?
?- min(5,7,X).
?- min(5,X,7). % false
?- min(X,5,7). % false
?- min(X,Y,7). % error – why?
Predicates using Recursion: power
• Positive Powers
– boundary case for power to 1
pow( X, 1, X ).
– recursion to calculate the product
pow( X, Y, Z ) :- Y > 1,
Y1 is Y - 1,
pow( X, Y1, Z1 ),
Z is X * Z1.
Predicates using Recursion: gcd
• Greatest common divisor
– Boundary condition
• gcd of 0 and any number is the number itself
gcd(U,0,U).
– Recursive clause based on Euclid’s algorithm
• modulo divisions until remainder is 0 at which point
we found a divisor for all intermediate divisors and
the original number
gcd(U,V,W) :- V>0, R is U mod V,
gcd(V,R,W).
• Alternative implementation of Euclid’s algorithm
gcd(A,A,A).
gcd(A,B,GCD):- A<B, NB is B-A, gcd(A,NB,GCD).
gcd(A,B,GCD):- A>B, NA is A-B, gcd(NA,B,GCD).
Animation of Euclid’s Algorithm
gcd(1071,462,W) :-
462>0, 147 is 1071 mod 462,
gcd(462,147,W) :-
147>0, 21 is 462 mod 147,
gcd(147,21,W) :-
21>0, 0 is 147 mod 21,
gcd(21,0,W).
W = 21.
• Arithmetic Expressions
– Built-in operators
– Unification with numbers
• Recursive calculations
• power, factorial, gcd, fibonacci
• crossed recursion
• Generator