Append forms a new list by successively consing the elements of x onto y. The procedure append! is similar to append, but it is a mutator rather than a constructor. It appends the lists by splicing them together, modifying the final pair of x so that its cdr is now y. (It is an error to call append! with an empty x.)
Here last-pair is a procedure that returns the last pair in its argument:
Consider the interaction
What are the missing <response>s? Draw box-and-pointer diagrams to explain your answer.
Answer:
Exercise 3.13. Consider the following make-cycle procedure, which uses the last-pair procedure defined in exercise 3.12:
Draw a box-and-pointer diagram that shows the structure z created by
What happens if we try to compute (last-pair z)?
Answer: Terrible things happen!
Make-cycle
creates a circular list. This is not a bad thing to have and might actually come useful under some circumstances. However trying to compute (last-pair z)
throws the interpreter into an infinite loop.
Exercise 3.16. Ben Bitdiddle decides to write a procedure to count the number of pairs in any list structure. ``It's easy,'' he reasons. ``The number of pairs in any structure is the number in the car plus the number in the cdr plus one more to count the current pair.'' So Ben writes the following procedure:
Show that this procedure is not correct. In particular, draw box-and-pointer diagrams representing list structures made up of exactly three pairs for which Ben's procedure would return 3; return 4; return 7; never return at all.
Answer:
Exercise 3.18. Write a procedure that examines a list and determines whether it contains a cycle, that is, whether a program that tried to find the end of the list by taking successive cdrs would go into an infinite loop. Exercise 3.13 constructed such lists.
Answer:
No comments:
Post a Comment