CSC 151-02, Fall 2006 : Schedule : Lab 37


Lab 37: Objects in Scheme

Summary: In this lab, we consider techniques for building objects, collections of data that support operations on those data.

Contents:


Exercises

Exercise 1: Testing Switches

a. Make a copy of the make-switch procedure from the reading.

b. Test the switches created by the make-switch procedure. Here are a few possible instructions.

> (define lamp-switch (make-switch))
> (define vacuum-cleaner-switch (make-switch))
> (lamp-switch ':show-position)
> (vacuum-cleaner-switch ':show-position)
> (lamp-switch ':toggle!)
> (lamp-switch ':show-position)
> (vacuum-cleaner-switch ':show-position)
> (lamp-switch ':toggle!)
> (vacuum-cleaner-switch ':toggle!)
> (lamp-switch ':show-position)
> (vacuum-cleaner-switch ':show-position)

Exercise 2: A Single Tally Object

Define a one-field object, tally, that responds to exactly four messages:

The initial value of the field should be 0.

For example,

> (tally ':set-contents-to-zero!)
> (tally ':show-contents)
0
> (tally ':increment!)
> (tally ':show-contents)
1
> (tally ':decrement!)
> (tally ':decrement!)
> (tally ':decrement!)
> (tally ':show-contents)
-2

Note that you are creating a single object, not a procedure that creates objects.

Exercise 3: Making Generic Tallys

a. Define a make-tally procedure that constructs and returns objects similar to the tally object you defined in exercise 2.

b. Create two tally objects and demonstrate that they can be incremented and reset independently.

Exercise 4: Tallys with Initial Values

Write a new make-tally procedure that allows the client to create new tallys with a specied initial value. For example, I might say that a starting grade is 90 with

> (define grade (make-tally 90))

I would then increment and decrement it as students do good or bad work.

Exercise 5: Monitored Tallys

a. Define a constructor procedure, make-monitored-tally, for objects similar to the tally objects from exercise 2 above, except that each such object keeps track of the total number of messages that it has received.

Hint: For this exercise, you will want to make a two-element vector. Element 0 of that vector will be the value of the tally. Element 1 of that vector will be the count of operations.

b. Test your procedure.


Janet Davis (davisjan@cs.grinnell.edu)

Created November 21, 2006 based on http://www.cs.grinnell.edu/~rebelsky/Courses/CS151/2006F/Labs/objects.html
Last revised November 21, 2006
With thanks to Sam Rebelsky