Comp 210 Lab 3: define-struct

Index: define-struct, Kingdom example


define-struct

How would you represent a "pair" in Scheme? An "association", from homework, was just a special kind of pair, for example. So far, we would have represented it as a two-element list. Well, that seems kind of strange:

This lab introduces a way to define new ways to structure your data.

First, congratulations you have graduated to DrScheme's "intermediate" language level! What we will be introducing isn't allowed in the beginner level. In DrScheme, select Configure Language Level from the Language Level menu. Choose Intermediate from the resulting menu. Restart DrScheme.

OK, back to pairs. What are the important things about pairs? Most importantly, they contain exactly two elements. Also, it would be nice to have helper functions like Scheme provides for numbers, lists, etc.:

Scheme gives us a way to define all of that at once: (define-struct pair (first second)). This defines several functions:

But what is the "pair"? Well, all we care about is that it has two elements in it and that we can make them, test them, and look inside them. Do we care what they really are inside the computer? You'll notice that the result of (make-pair 1 2) does not print as (cons 1 (cons 2 empty)). In fact, Scheme considers the two to be distinct values.

Would it matter if we had typed (define-struct pair (second first)), instead?

Defining structures in Donkey

Alas, whereas DrScheme uses define-struct, Donkey uses something slightly different.

You'll need to change your program if you want to use Donkey's single-stepping ability when debugging.


Kingdom example

Consider the following data definition, which describes the structure of a medieval kingdom:

Do the following, answering the questions. When you're done, you can look at the answers.

A hint of mutual recursion

You haven't seen this in lecture yet, but here's something to think about.

Let's add to our data definition:

This introduces mutual recursion: There is a loop in the dependencies: regent is defined in terms of knight, which is defined in terms of serf, which is defined in terms of regent.

How would we change our potato-counting program? (Spies steal potatoes.)

Write a function that checks if a kingdom has any spys working against it. The function should take a regent as its argument and return a boolean.

Create test data for this function.

This example requires a lot of test data to be fully complete.