2-csc407 prolog lab 2
2-csc407 prolog lab 2
Faculty of Science
CSC 405 – Artificial Intelligence
Prolog Laboratory Sheet II
Exercises
Define predicates to calculate the following:
• the result of adding 1 to a number
• the function signum(x) which is x-1 if x>0, and 0 otherwise
• the absolute value of a number
• the product of two numbers
• the sum of two numbers
• division of two numbers
• integer division of two integers (div)
• remainder of division of two integers (mod)
• the maximum of two numbers
• the maximum of three numbers (without using recursion)
Using Recursion
Recursion is extremely important in Prolog. Iteration constructs like while, do, for, etc. that are provided in imperative
programming languages like C, C++, Java, are not available in Prolog. If we want to iterate in Prolog, we use recursion.
Recursion involves defining something in terms of itself. The key to ensuring that this makes sense is that you always define
something in terms of a smaller copy of itself. Recursion is the algorithmic equivalent of “proof by induction” in mathematics.
When you do recursion you must have three things:
1. Some set (or "data structure") over which you are doing the recursion: common examples include numbers, arrays,
trees etc.
2. A base case definition, usually dealing with an empty structure
3. A recursive case definition, explaining how to work out a non-trivial case in terms of some smaller version of itself.
Some Examples
Factorial:
By definition, the factorial of some positive integer n, written n! is n*n-1*n-2* ... *1. We can express this in terms of recursion
as follows:
Data Structure: natural numbers
Base Case: fact(0) = 1
Recursive Case: For any n>0, we have fact(n) = n * fact(n-1)
Test for Even Numbers:
Data Structure: natural numbers
Base Case: 0 is even
Recursive Case: For any n>0 we know that n is even only if n-2 is even.
A similar definition can be used to test if a number is odd; here the base case will be 1.
Maximum of three numbers: X, Y, Z
Base case: Maximum of 2 numbers
Recursive case: Determine maximum of X,Y = W, then determine maximum of W, Z.
Basically, transfer(N,A,I,B) will be satisfied if we can find an algorithm to transfer N discs from A to B using I. The
following code can be used.
% transfer(N,A,I,B) is true if we can transfer N discs from A to B
% using I as an intermediate peg.
% Base case - 1 disc
transfer(1,A,I,B) :- move(A,B).
% Recursive case - N discs
transfer(N,A,I,B) :-
M is N-1,
transfer(M,A,B,I), %Transfer top N-1 discs from A to I, using B
move(A,B), %Move biggest disc from A to B
transfer(M,I,A,B). %Xfer remaining N-1 discs from I to B using A
Create a KB with the code given above, and name it hanol.pl.
Test your KB with a queries of the form:
transfer(3,a,b,c).