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.

  1. Let the on relation mean that one thing is resting directly on another. Write a rule above(X,Y) that is true when X is somewhere above Y.
    1. above(X,Y) :- on(X,Y).
      above(X,Y) :- on(Z,Y), above(X,Z).
      
  2. The following facts represent some "likes" among the Mariners.
  3.     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).
  4. Define the rule(s) for the predicate sumlist(L,S) so that S is the sum of the list of numbers L.
    1. sumlist([],0).
      sumlist([X|Xs],Y) :- sumlist(Xs,Z), Y is X + Z.
  5. THIS PROBLEM IS EXTRA CREDIT. Define the rule(s) for the predicate delete(L,E,NoEs), where the list NoEs is the result of removing all occurrences of element E from list L.
    1. 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)