Prolog Programming Assignment Solutions
This document contains solution code for the CSE341 prolog programming assignment. Note that there are many ways to implement the same idea. I present only one here, but others are equally valid.
above(X,Y) :- on(X,Y). above(X,Y) :- on(Z,Y), above(X,Z). likes(junior, jay).
likes(junior, alex).
likes(lou, junior).
likes(lou, alex).
(a) Write a universal fact that says, "Everyone likes junior." likes(X,junior). (b) Write a rule important(X) that says, "X is important if junior likes X." important(X) :- likes(junior,X). (c) Write a rule very_important(X) that says, "X is very important if X is important and lou likes X." very_important(X) :- important(X), likes(lou, X). sumlist([],0). sumlist([X|Xs],Y) :- sumlist(Xs,Z), Y is X + Z. delete([],X,[]). delete([X|Xs],X,Ys) :- delete(Xs,X,Ys). delete([X|Xs],Z,[X|Ys]) :- X \== Z, delete(Xs,Z,Ys). Notes: This was the hardest problem of the assignment. There were a few very common errors in coding delete. First, a number of people had rules that remove the first matching element and leave the rest of the list alone. For example, delete([X|Xs],X,Xs). This rule answers "yes" to the query delete([1,2,3,1],1,[2,3,1]). Recall that all occurences must be removed. Another common problem, was to not include the X \== Z part of the third rule above. This omission allows the prolog interpreter to select that rule even when X and Z are the same. As a result, X is not removed from the list in the third argument. If you did this, try out the query delete([1,2,1,3],1,[1,2,1,3]). The interpreter will answer "yes."
echris@cs.washington.edu (10/31/96) |