Skip to main content

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

Structured Data

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 called data:

    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, and pages) that returns a new piece of data of type BookRecord. Functions like book are known as constructors.

  • 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-dispossessed.pages # evaluates to 387

Class Exercise (45 mins)

  1. Design a function that returns a "summary string" for a book, including the title, author, and pages.

  2. Design a function is-long-book that returns whether or not the book has more than 350 pages.

  3. 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.

  4. Design a podcast-summary that produces a string summarizing a Podcast.

  5. Design a Recipe data definition, and then write a row-to-recipe function that consumes a Row from 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
  6. Test your function using recipes.row-n(0) or some other row number, and then use it to add a new column with build-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.