Assignment 4

Assignment 6

List processing in Prolog

Goals

To understand and use techniques for programming in Prolog.

1. Write a Prolog predicate to reverse a list. e.g. given the goal reverse([a,b,c],R), Prolog will respond with R=[c,b,a].

2. Write a Prolog predicate to square the items in a list of integers. e.g. given the goal squareList([1,2,3],L), Prolog will respond with L=[1,4,9].

Hints

1. You will need to use append, as given in class, to help with reverse.

2. To make a list out of an item, just put it in square brackets. e.g. a list of a single item bound to X is [X].

3. Arithmetic needs the 'is' operator, e.g. X is Y + Z will add the values bound to Y and Z and the result is bound to X.

Deliverables

A listing of your source code with the appropriate predicates defined, and a trace of the predicates running. Use the above goals for the final tests that you turn in. i.e.

reverse([a,b,c],R).

squareList([1,2,3],L).

Due Date

Wednesday, April 30th. before midnight

Running sicstus prolog

The version of Prolog which you will use is called sicstus (there was a quintus before it). It runs under Linux. You can put sicstus in your path with:

% source /local/config/cshrc.sicstus

and then run the interpreter with

% sicstus

You will get something like the following response:

SICStus 3.12.2 (x86-linux-glibc2.3): Sun May 29 11:59:09 CEST 2005
Licensed to cs.nmsu.edu
| ?-

You can then type in a goal for Prolog to try and satisfy. Prepare your Prolog programs with any text editor, and then load the file (Prolog calls it 'consulting') with:

| ?- ['myfile.plg'].

This will load your file and give you the prompt back. Don't forget the period at the end! Let's say you put the append predicate in a file called append.plg. You could then load it and run append with

| ?- ['append.plg'].
{consulting /pathto/directory/append.plg...}
{consulted /pathto/directory/append.plg in module user, 0 msec 976 bytes}
| ?- append([a,b,c],[d,e],L).

L = [a,b,c,d,e] ?

yes
| ?-

Exit sicstus by typing

| ?- halt.

or pressing ctrl-D.