Day 18 - Structured data
Skills: 4
Pre-reading: 6.1.1.1, 6.1.2.1, 6.1.2.2, 6.1.3.1
Supplementary Videos
Intro (10 mins)
-
Many pieces of information consist of multiple parts that should be kept together.
-
e.g., in tables, the row consists of several values. But, this same idea is useful outside of tables.
-
Consider, for example, a record of a book used by a library program -- which has a title, author, and number of pages.
-
We can define a new type of data for a
BookRecordusing a language feature calleddata:data BookRecord:
| book(title :: String, author :: String, pages :: Number)
end -
This defines both the type of data (
BookRecord), for use in type annotations, and a way of constructing it --book, which is a function of three arguments (title,author, andpages) that returns a new piece of data of typeBookRecord. Functions likebookare known as constructors. -
For example, we can create three
BookRecordsas: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) -
The field names are used to access the parts of the
BookRecord, using the dotted "field access" notation:the-dispossessed.pages # evaluates to 387
Class Exercise (45 mins)
-
Design a function that returns a "summary string" for a book, including the title, author, and pages.
-
Design a function
is-long-bookthat returns whether or not the book has more than 350 pages. -
Design a new data type for a
Podcast, and based on your own knowledge figure out the fields that make sense to include in it. -
Design a
podcast-summarythat produces a string summarizing aPodcast. -
Design a
Recipedata definition, and then write arow-to-recipefunction that consumes aRowfrom the following table (be sure to sanitize columns as needed):include csv
include data-source
recipes = load-table:
title :: String,
servings :: Number,
prep-time :: Number
source: csv-table-url("https://raw.githubusercontent.com/neu-pdi/cs2000-public-resources/refs/heads/main/static/support/5-recipes.csv", default-options)
sanitize servings using num-sanitizer
sanitize prep-time using num-sanitizer
end -
Test your function using
recipes.row-n(0)or some other row number, and then use it to add a new column withbuild-column.
Wrap-up (5 mins)
- Structured data groups multiple fields together.
- We define structured types using
dataand create instances by calling the constructor. - Fields are accessed with the dot notation.