Pairs and pair structures

Course links

Exercise 1

Draw box-and-pointer diagrams for each of the following lists:

Exercise 2

Have DrScheme evaluate each of the following expressions. In each case, explain why Scheme does or does not use the dot notation when displaying the value.

Exercise 3

Draw a box-and-pointer representation of the value of each expression in the previous exercise.

Exercise 4

Define and test a procedure named cons-cell-count that takes any Scheme value and determines how many boxes would appear in its box-and-pointer diagram. (The data structure that is represented by such a box, or the region of a computer's memory in which such a structure is stored is called a cons cell. Every time the cons procedure is used, explicitly or implicitly, in the construction of a Scheme value, a new cons cell is allocated, to store information about the car and the cdr. Thus cons-cell-count also tallies the number of times cons was invoked during the construction of its argument.)

For example, the structure in the last box-and-pointer diagram shown above contains seven cons-cells, so when you apply cons-cell-count to that structure, it should return 7. On the other hand, the string "sample" contains no cons-cells, so the value of (cons-cell-count "sample") is 0.

Use cons-cell-count to find out how many cons cells are needed to construct the list (0 (1 (2 (3 (4))))). Draw a box-and-pointer diagram of this list to check the answer.

Exercise 5

Define and test a procedure called pair-structure-max that takes any Scheme value as its argument, and returns the greatest exact positive integer contained in that value (considered as a pair structure), or 0 if the structure contains no exact positive integers.

In other words, if pair-structure-max is given an exact positive integer, it should return that argument unchanged; if it is given a pair, it should apply itself recursively to the pair's car and cdr, and return whichever result is larger; and otherwise it should return 0.

> (pair-structure-max 17)
17
> (pair-structure-max '((3 . 1) . (4 . (5 . 2))))
5
> (pair-structure-max '())
0
> (pair-structure-max "foo")
0
> (pair-structure-max '(((-3 . "bar") . 17.9) . (baz . #f)))
0

The principal author of this lab is Professor Henry Walker. I am also indebted to Professor Ben Gum for his contributions to its development.