CS 224 Lab 4 - Prolog

Objectives:

  • Write basic prolog relations
    1. Login to your account on phoenix. Copy the files lab6_1.pl and lab6_2.pl from the directory ~jillz/cs224 .
       
    2. Enter prolog by the command
              swipl
      Now load in the file lab6_1.pl as follows
             [lab6_1].
       
    3. Take a look at the file lab6_1.pl. This file defines the relation ancestor. We will try a few queries that use this relation. Before you type each query, try to figure out what you think prolog will answer.
              ancestor(amy,bob).
              ancestor(bob, amy).

    For the query
            ancestor(X,bob).
    there are two possible values of the variable X which make this query true. Prolog will print the first that it finds. If you then type a semicolon , prolog will look for another possible value for X. Type a semicolon once more and prolog will search for another answer and this time fails.
    Note: Variables in prolog are always capitalized and constants are always lower case.

    1. Terms in prolog can be used to create data structures. We will use a term node(X,L,R) to represent a binary search tree with root value of X and left and right subtrees L and R respectively. Recall that all the values in the left subtree are less than the root value and that all the values in the right subtree are greater than the root value. Also the left and right subtrees are both binary search trees.

    Assignment:

    Write a relation membst which determines whether a value K is a member of a binary search tree.

    Test your relation with the following queries:
      
    membst(3,node(5,node(3,nil,nil),node(7,nil,nil))).
       membst(6, node(5,node(3,nil,nil),node(7,nil,nil))).

     

    1. Prolog allows lists to be represented by a term such as [X|Y], where X is the head of the list and Y is the tail. Take a look at the file lab6_2.pl. This file contains a relation append2 which appends two lists. The relation takes three arguments so that append2(A,B,C) is true if the list A appended to the list B results in the list C. Consult this file in prolog and the try the following query:
              append2([1,2],[3,4],A).
      Because this is a relation rather than a function, we can use variables as the first two arguments in queries. Try finding all possible answers to the following query by using the semicolon.
              append2(X,Y,[1,2]).
       
    2.  Take a look at the relation reverse1. Try it out and make sure that you understand why it works

    Assignment:

    Write a relation which may be used to find the last item in a list.

     


    1.  

      Assignment:

      Section 19.10 in the text describes "What Prolog is Good For" with an example of a little puzzle. Read this section and copy the file manwolf.pl from ~jillz/cs224 and complete exercise 21 on p412