next up previous
Next: About this document ... Up: CS212 Preliminary Exam I Previous: Induction (20 points)

Abstraction and Class Definitions (21 points)

A queue is a container with the property that the first thing inserted into the queue is the first object that can be removed from the queue. That is, queues are First-In, First-Out (FIFO) containers.

You are asked to implement the following contract for queues:

     type: <queue>
     (make-queue)   --  creates a new, empty queue
     (empty? q)     --  returns #t if the queue is empty
     (insert x q)   --  takes an object x and a queue q and returns a new queue
                          with x inserted into the queue
     (front q)      --  returns the front of the queue.  that is, the first
                          object in the queue.
     (remove q)     --  returns a new queue with the front removed.

The contract requires that the following equivalences hold:

     (empty? (make-queue)) = #t
     (empty? (insert x q)) = #f

     if (empty? q) = #t, then (front (insert x q)) = x and
                              (remove (insert x q)) = q

     if (empty? q) = #f, then (front (insert x q)) = (front q) and
                              (remove (insert x q)) = (remove q).

In what follows, you will define a class for queues and methods for make-queue, empty?, insert, front, and remove.

a.
class definition:

(define-class <queue> (<object>) (elts <list>))

b.
make-queue definition:

(define (make-queue <function>) (method () (make <queue> elts: '())))

c.
empty? definition:

(define (empty? <function>) (method (q <queue>) (null? (elts q))))

d.
insert definition:
(define (insert <function>)
  (method ((x <object>) (q <queue>))
    (make <queue> elts: (append (elts q) (cons x '())))))
e.
front definition:
(define (front <function>) (method ((q <queue>)) (head (elts q))))
f.
remove definition:
(define (remove <function>) 
  (method ((q <queue>)) 
    (make <queue> elts: (tail (elts q)))))

next up previous
Next: About this document ... Up: CS212 Preliminary Exam I Previous: Induction (20 points)
Gregory Morrisett
3/11/1998