Day 17 - Structured data
Skills: 4
Pre-reading: 6.1.1.1, 6.1.2.1, 6.1.2.2, 6.1.3.1
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
BookRecord
using 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
. - For example, we can create three
BookRecords
as: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-disposesssed.pages # evaluates to 387
Class Exercise (40 mins)
- Design a function that returns a "summary string" for a book, including the title, author, and pages.
- Design a function
is-long-book
that returns a boolean if the book has more than 350 pages. - Design a new data type for a
Podcast
, and figure out the fields that make sense to include in it. - Design a
podcast-summary
that produces a string summarizing aPodcast
. - Design a
Recipe
data definition, and then write arow-to-recipe
function that consumes aRow
from the following table:include csv
recipes = load-table:
title :: String,
servings :: Number,
prep-time :: Number
source: csv-table-url("https://pdi.run/f25-2000-recipes.csv", default-options)
end - Test your function using
recipes.row-n(0)
or some other 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
data
and create instances by calling the constructor. - Fields are accessed with the dot notation.