

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


CS 403/503 Exam 4 Fall 2007 Solution
V=a, W=d V=a, W=e V=a, W=c V=b, W=d V=b, W=e V=b, W=c V=c, W=d V=c, W=e V=W
f([[2],3], M)
f([2], X) f([3], Y) (^) M is X+Y = 2+3 = 5
f(3,3) f([ ],0) Y is 3+0 = 3
number(3)
f(2,2) f([ ],0) X is 2+0 = 2
number(2)
a. last(L, X) is satisfied when X is the final element of list L. Example: last([2,3,4,5,6,7], X) yields X = 7.
last([X], X). last([ _|T], X) :- last(T, X).
b. removelast(L, L2) is satisfied when L2 is formed from list L by discarding the final element of L. Example: removelast([2,3,4,5,6,7], Y) yields Y = [2,3,4,5,6].
removelast([ _ ], [ ]). removelast([H|T], [H|T2]) :- removelast(T, T2).
c. rightcycle(L, Z) is satisfied when Z is formed by circularly rotating the elements of list L one position to the right. Example: rightcycle([2,3,4,5,6,7], Z) yields Z = [7,2,3,4,5,6].
rightcycle(L, [X|Y]) :- last(L, X), removelast(L, Y).
d. neglist(A, B) is satisfied when A is a list of numbers, and B is obtained by negating each value of A. Example: neglist([-1,2,-3,4,-5,6], L) yields L = [1,-2,3,-4,5,-6].
neglist([ ], [ ]). neglist([H|T], [H2|T2]) :- H2 is - H, neglist(T, T2).
e. negvalues(A, B) is satisfied when A is a list of numbers, and B contains the negative values of A. Example: negvalues([-1,2,-3,4,-5,0], L) yields L = [-1,-3,-5].
negvalues([ ], [ ]). negvalues([H|T], L) :- H>=0, negvalues(T, L). negvalues([H|T], [H|L]) :- H<0, negvalues(T, L).
f. addlists(X, Y, Z) is satisfied when list Z is obtained from lists X and Y by adding the corresponding numbers. Example: addlists([2,3,4,5], [6,7,8,9], L) yields L = [2+6, 3+7, 4+8, 5+9] = [8,10,12,14].
addlists([ ], [ ], [ ]). addlists([H|T], [H2|T2], [H3|T3]) :- H3 is H+H2, addlists(T, T2, T3).