Proper Treatment 正當作法/ cs504/ 2009/ Homework: the same-fringe problem
2009-01-29 15:14

(Please do this homework in pairs or triples.)

Let’s say a tree is either a list of two trees or a number. For example, here are two trees.

(((1 2) (3 4)) (5 6))
(1 (((2 3) (4 5)) 6))

Although these are two different trees, they have the same fringe. The fringe of a tree is the list of numbers at its leaves, from left to right. In contrast, the following tree has a different fringe.

(6 (((2 3) (4 5)) 1))

The goal of this homework is to write a function same-fringe? that takes two trees as input and checks to see if they have the same fringe. A simple way to write such a function, and the way you should start, is to write a helper function that takes one tree as input and computes its fringe. But if two trees’ fringes differ at the very beginning, it would be nice for our same-fringe? function to return #f right away, without going through the rest of the trees (which may be large). To implement this nicety, express the process of enumerating the leaves of a tree from left to right as a state space and a transition function.

More advice

After you decide how to represent a state, I expect your solution to specify two things: (1) how to turn a tree into an initial state; and (2) given a state, whether it is “final” (that it, whether any leaf nodes remain to be enumerated), and if it is not final, what is the next leaf node and what is the next state. For this exercise, it may be slightly easier to split (2) into three parts: a test to check if a state is final; a function from a non-final state to a leaf number; and a function from a non-final state to its next state. But in other situations, it is much easier for a single function to simultaneously compute all the information in (2).

Once you’re done with (1) and (2), you can define the main same-fringe? function. If you find it tricky to write, try something simpler first: write a function to count how many leaves a single given tree has.

Be sure your code works when