Skip to main content

Practice Problems: Structured & Conditional Data (Pyret)

Tests are given for all practice problems for you to run against your own implementation.

Problem Statement: Create a data structure to represent a book and write functions to work with it.

Part A: Define the Data Define a Book data type with fields for title (String), author (String), pages (Number), and year (Number).

Part B: Create Functions Write the following functions:

  1. book-age - calculates how old a book is (2025 - year)
  2. is-long-book - determines if a book has more than 400 pages
  3. format-book-info - creates a formatted string with book information

Template:

# Part A: Define the data
data Book:
# write your data definition here, call it `book`
end

# Part B: Create functions

fun book-age(b :: Book) -> Number:
# write your function here
where:
book-age(book("1984", "George Orwell", 328, 1949)) is 76
book-age(book("Recent", "Author", 200, 2020)) is 5
book-age(book("Brand New", "Author", 150, 2024)) is 1
end

fun is-long-book(b :: Book) -> Boolean:
# write your function here
where:
is-long-book(book("Long Book", "Author", 500, 2000)) is true
is-long-book(book("Short Book", "Author", 200, 2000)) is false
is-long-book(book("Exactly 400", "Author", 400, 2000)) is false
is-long-book(book("Just Over", "Author", 401, 2000)) is true
end

fun format-book-info(b :: Book) -> String:
# write your function here
where:
format-book-info(book("1984", "George Orwell", 328, 1949)) is "1984 by George Orwell (1949)"
format-book-info(book("Test", "Author", 100, 2000)) is "Test by Author (2000)"
end