M05: Structures

Hint: If possible, make your browser wide enough to place the slides and commentary side-by-side.

The slides on this page are not accessible (for screen readers, etc). The 1up and 3up slides are better.

Module Topics

  1. Compound data
  2. Formalities: Syntax and semantics
  3. Templates
  4. Nested Structures
  5. Mixed Data
Slide 000
Slide 001

The idea of compound data has been around for a very long time. Our presentation of compound data in CS135 and the language we use to describe it is heavily influenced by Object-Oriented Programming, a programming paradigm you’ll learn more about in CS246 (typically a 2A course).

This module was completely rewritten for Fall 2024, so the commentary is still a little sparse :(

Slide 002
Slide 003
Slide 004
Slide 005
Slide 006
Slide 007
Slide 008

Here’s an example of the substitution rules in action.

Slide 009

We need to figure out the substitution rules for structures. This slide formalizes what we’ve said previously to prepare for the rules on the next slide.

Slide 010
Slide 011

The define-struct is followed by a data definition that says what types each of the structure’s fields are expected to be. The data definition for a structure is of the form

;; A <type-name> is a (make-<sname> <type> ...)

where you fill in the parts between angle brackets. <sname> is the first argument to define-struct.

The relationship between the define-struct and its data definition is similar to a function and its contract. Just as you wouldn’t dream of writing a function without a contract, you shouldn’t have a structure definition without a data definition.

The data definition is just a comment, so it has no meaning to Racket. Therefore, Racket does not know what types we expect each field to have. It can’t check, for example, that the description is a string and that prices and available should be numbers.

Slide 012
Slide 013
Slide 014

The fields are listed in the same order in the template as in the define-struct so a new structure can be easily constructed with them.

Students who have programmed in an imperative language will often ask how to change the contents of a field. The answer is that you don’t. You create a new structure with the same information except for the field(s) you want to change.

Slide 015
Slide 016
Slide 017
Slide 018
Slide 019
Slide 020
Slide 021
Slide 022
Slide 023
Slide 024
Slide 025
Slide 026
Slide 027
Slide 028
Slide 029
Slide 030
Slide 031
Slide 032
Slide 033