Trace calls across nested data definitions

A file browser uses two data definitions:

  • Item is either File(size) or Folder(contents). File sizes are non-negative integers in bytes, and folder contents are an ItemList.
  • ItemList is either Empty() or Cons(first, rest), where first is an Item and rest is another ItemList.

Each folder's list contains exactly its immediate children. A list of three children therefore has three Cons values followed by one Empty(). The structure shown has no shared items or cycles.


A root folder contains a file, an empty folder, and a folder containing one file.


The following Python function templates use pattern matching: each case selects a data form and gives names to its fields.


Python
def scan_item(item):
    match item:
        case File(size):
            return 1
        case Folder(contents):
            return scan_list(contents)


def scan_list(items):
    match items:
        case Empty():
            return 0
        case Cons(first, rest):
            return scan_item(first) + scan_list(rest)


Starting with scan_item(root), determine the total number of calls to scan_item, the total number of calls to scan_list, and the number of scan_list calls whose input is Empty(). Include the initial call and every terminating call. Give all three counts as exact integers.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Data Definitions and Program Structure Questions: