Day 18 - Structured data
Introduction to Structured Data
1. Introduction (10 minutes)
-
Overview:
- Explain that many pieces of real‑world information consist of several parts that should be kept together.
- Introduce the idea of structured data—data that bundles multiple fields (attributes) into a single value.
-
Example Context:
- A library system where each book has a title, an author, and a page count.
-
Learning Goals:
- Understand what structured data is.
- Learn how to define a new structured type in Pyret.
- Create and annotate instances of structured data.
- Write functions to extract fields from structured data.
-
Do Now:
- Ask: “What kinds of information in your daily life are made up of several parts? (e.g., a contact entry, a recipe, a product listing)”
- Briefly share examples with the class.
2. Defining and Creating Structured Data (20 minutes)
-
Defining a Structured Data Type:
- Introduce a new data type called
BookRecord
to represent a book. - Pyret Code:
# Define a structured type for a book with three fields: title, author, and pages
data BookRecord:
| book(title :: String, author :: String, pages :: Number)
end
- Introduce a new data type called
-
Creating Examples:
- Create instances of
BookRecord
using the constructorbook
. - Examples:
# Create some book records
the-dispossessed = book("The Dispossessed", "Ursula K. Le Guin", 387)
to-the-lighthouse = book("To the Lighthouse", "Virginia Woolf", 209)
brave-new-world = book("Brave New World", "Aldous Huxley", 268)
- Create instances of
-
Annotations for Structured Data:
- Emphasize that field annotations (e.g.,
title :: String
) help catch type errors.
- Emphasize that field annotations (e.g.,
-
Interactive Exercise:
- Ask: “What do you expect to happen if you try to create a book with a non-number for pages?”
- Discuss potential type errors and the role of annotations.
3. Programming with Structured Data (20 minutes)
-
Extracting Fields:
- Write a function that returns a summary string for a book.
- Example Function:
fun book-summary(b :: BookRecord) -> String:
# We can access fields using dot notation (e.g., b.title)
b.title + " by " + b.author + " (" + string-from-number(b.pages) + " pages)"
end
-
Interactive Exercise:
- Ask: “What is the result of
book-summary(the-disposessed)
?” - Expected output:
"The Disposesssed by Ursula K. Le Guin (387 pages)"
.
- Ask: “What is the result of
-
Additional Exercise:
- Write a function
is-long-book
that returns true if a book has more than 350 pages. - Example Implementation (guided by class discussion):
fun is-long-book(b :: BookRecord) -> Boolean:
b.pages > 350
end - Test with
the-disposessed
andbrave-new-world
.
- Write a function
4. Wrap-Up (10 minutes)
- Recap Key Points:
- Structured data groups multiple fields together.
- We define structured types using
data
and create instances by calling the constructor. - Fields are accessed with the dot notation.