CS 291 University of Puget Sound Spring, 2020
 
Programming Language Paradigms:
Explorations with Functional Problem Solving (supported by Scheme/Haskell)
and Declarative Prblem Solving (supported by Prolog)
 

Prolog Worksheet 2, due Monday, April 20


Problems for this Worksheet 2 with Prolog

  1. Lists of Even Length: Write a Prolog rule for a list Lst that succeeds if and only if Lst has an even number of elements. Rather, think patterns and recursion!

    Notes:

  2. Elements in Even and Odd Positions within a List: Write a Prolog rule evensOddsList(Evens, Odds, Lst) which succeeds if Evens is a sublist of Lst containing (in order) the elements in even positions of Lst (using 0-based indexing), and Odds is a sublist containing the elements in odd positions.

    Examples

          evensOddsList([a,c,e], [b,d,f], [a,b,c,d,e,f]).
              yields true
          evensOddsList([[b,d,f], a,c,e], [a,b,c,d,e,f]).
              yields false
          evensOddsList(Evens, Odds, [a,b,c,d,e,f,g]).
              yields Evens == [a,c,e,g] and Odds == [b,d,g]
        
  3. Merging Two Sorted Lists: Assuming Lst1 and lst2 are two lists with elements in ascending order, write a rule merge(Lst1, Lst2, Result that succeeds if Result is the list obtained when Lst1 and lst2 are merged into a single ordered list.

    Note:

  4. Merge Sort: Use the evensOddsList rule of problem 2 and the merge rule from problem 3, to write a rule to perform a merge sort.

    Note:

  5. Search Trees: Draw Prolog search trees for the query

          reverse([a,b,c,d], W).
        

    where reverse is defined bu the following sets of rules.

    1.           reverse([ ], [ ]).
                reverse([A|X], Z :- reverse(X, Y), append(Y, [A]. Z).
              
    2.           reverse(X, Z) :- rev(X, [ ], Z).
                rev([ ], Y, Y).
                rev[A|X], Y, Z) :- rev(X, [A | Y], Z).
              

    Logistics

  6. Intersection of Two List Parameters: Wrote a Prolog rule (with helper rules, if needed), that succeeds if the intersection of two given list parameters is empty—that is, if no element on the first list is an element anywhere in the second list.

Extra Credit Problem

  1. Retrieving Elements of a List Before a Given Item: Write a Prolog rule beforeWord(Item, Lst, Result) which succeeds when Result contains exactly those elements of the list Lst (in order) which appear before the Item.

    Examples:

         beforeWord(is, [computer, science, is, fun], Result]
            ==>  [computer, science'
         beforeWord(math, [computer, science, is, fun], Result]
            ==> fails
      

    Notes:


created 10 April 2020
revised 13 April 2020
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.