Deep recursion

Course links

Exercise 1

Define and test a procedure count-this-symbol that takes two arguments, the first a list and the second a symbol, and computes and returns the number of occurrences of the specified symbol anywhere inside the given list (including nested lists). (Hint: use count-all-symbols as a pattern.)

Exercise 2

Let's use the term ``tree of symbols'' for a datum like the one used in the preceding exercise -- specifically, a list in which each element is either a symbol or another tree of symbols. Define and test a predicate tree-of-symbols? that takes one argument and returns #t if the argument is a tree of symbols, #f if it is not. (Such a predicate would be useful in adding a precondition test to count-this-symbol.)

Exercise 3

Define and test a procedure sum-all that takes a tree of numbers -- a list in which each element is either a number or another tree of numbers -- and determines the sum of all the numbers in the tree.

Exercise 4

What is the depth of the datum (((a b) c) d (e (f)))? Why?

Exercise 5

Give an example of a tree of symbols of depth 7. Have DrScheme check your answer.

Exercise 6

Define a procedure depth-tally that takes two arguments, a tree of symbols tr and a positive integer level, and counts how many symbols occur inside tr at nesting level level exactly. (For example, in the tree of symbols (((a b) c) d (e (f))), the nesting level of the symbols c and e is 2, and the rest of the symbols have other nesting levels; so (depth-tally '(((a b) c) d (e (f))) 2) should yield 2.)

Exercise 7

Define a procedure weighted-depth that takes a tree of real numbers as its only argument and returns the result of multiplying each number in the tree by its nesting level and adding up all of the results.

I am indebted to Professors Henry Walker and Ben Gum for their contributions to the development of this lab.