This is an old revision of the document!


Introduction to Prolog programming

Consider the following representation of natural numbers (from our last lecture):

nat(zero).
nat(X) :- X = succ(Y), nat(Y).

1. Implement the predicate add/3 which adds two natural numbers. 2. Implement the predicate minus/3 which substracts one natural number from another. Substraction only needs to work as long as the result is a natural number.

Consider the following conversion predicates between naturals and Prolog integers.

toNat(0,zero).
toNat(X,succ(Res)) :- X>0, Xp is X-1, toNat(Xp,Res). 
 
fromNat(zero,0).
fromNat(succ(X),R) :- fromNat(X,Rp), R is Rp + 1. 

3. Implement min/3 which computes the minimum of two natural numbers. Example usage:

-? toNat(7,X), toNat(4,Y), min(X,Y,R), fromNat(R,O).

4. Implement max/3 which computes the maximum of two natural numbers. 5. Implement gt/2 which is satisfied if the first natural number is strictly greater than the second. 6. Implement leq/2 which is satisfied if the first natural number is less than or equal to the second. 7. Implement div/3 which implements the div operator. 8. Implement mod/3. 9. Implement gcd/3 which computes the greatest common divisor of two natural numbers.

Consider the following representation of lists, expressed by the predicate isList shown below.

isList(void).
isList(cons(_,T)) :- isList(T).

10. Implement head/2 and tail/2. 11. Implement size/2 which determines the length of a list as a Prolog integer. 12. Implement concat/3 which concatenates two lists. 13. Implement reverse/2 which reverses a list. Use accumulators instead of concatenation and an auxiliary predicate.

Consider the following conversion functions from the above list representation to Prolog lists.

fromList(void,[]).
fromList(cons(H,T),[H|R]) :- fromList(T,R).

14. Write the predicate toList/2 which converts a Prolog list to our list representation. 15. Implement kelem/3 which determines the k-th element of a Prolog list. 16. Implement rem/2 which removes consecutive duplicates from a Prolog list.

-? rem([1,1,1,2,2,3,4,4],R).
R = [1,2,3,4].

17. Implement flatten/2 which flattens nested Prolog lists. Do not use auxiliary predicates.

-? flatten([1,2,[3,4,[5]], [[6],[]], [7]], R).
 R = [1,2,3,4,5,6,7]

18. Implement pack/2 which groups consecutive duplicates into sublists.

?- pack([1,1,1,2,3,3,1,1,4,5,5,5,5],R).
 R = [[1,1,1],[2],[3,3],[1,1],[4],[5,5,5,5]]

19. Implement slice/4 which returns the elements of a list between two positions.

?- slice([1,2,3,4,5,6,7,8,9,10],3,7,R).
R = [4,5,6,7,8]

20. Implement rotate/3 which rotates a list by a given number of positions.

?- rotate([1,2,3,4,5,6,7,8],3,R).
R = [4,5,6,7,8,1,2,3]