Practice: Making Compound Data
by Matthias Felleisen
Structure definitions do not create data; they define functions for creating compound data. Given a structure definition, we sometimes say its constructor makes instances of the structure. With the selectors, it is possible to extract the values from certain compartments in compound data; these compartments are called fields or slots.
Copy and paste the following pieces of code into a DrScheme Definitions Window:Click RUN and create instances of
(define-struct foo (nothing)) (define-struct bar (kegs bouncers doors)) (define-struct pub (fries french))
pubin the Interactions Window. Remember that DrScheme just "returns" the expression that you enter if it is a value.
In reality, you almost never want to use all possible instances of structures in your program. Instead, you want to impose a data definition, which gives a name to the collection of all the structures that you really care about. Here are data definitions for the above structures:Check whether your instances from above are legitimate. Also, create three instances of
#| A Foo is one of: -- empty -- (make-foo Number) |# #| A Bar is a structure: (make-bar Number Number Symbol) |# #| A Pub is one of: -- Bar -- (make-pub Boolean Boolean) |#
Pubeach; if a data definition has clauses, make sure that you have at least one instance per clause.
Last but not least, you must be able to extract information from a value. Copy and paste the following structure definitions and examples into a Definitions Window and click RUN:In the Interactions Window, use the selectors for these structures to extract all the pieces from
(define-struct place (x y z)) (define place1 (make-place 10 20 -300)) (define-struct zone (time name summer)) (define zone1 (make-zone 300665 'eastern true)) (define-struct radio (station band sector)) (define radio1 (make-tv 'kabc 'am 1030))
You should be able to design those functions in 15 minutes. If you aren't, make up more exercises along those lines and practice! These kind of things must be at your finger tips by now. If you need such exercises and you can't make them, see the TAs during their office hours and ask them for suggestions.