3.21 Exercise 3.21
Ben expects the queue to be printed like a list, with the front item of the queue first and the rear item last. However, the queue data structure is not a list: It is merely a pair of pointers to lists. The REPL prints this as a pair, with the first entry being the list starting at the front pointer and the second being the list starting from the rear pointer (which only has one element). Deleting the first element of a two-element queue will make the front pointer and the rear pointer both point to a list of one item, for example.
Additionally, Ben is confused because removing all the entries from the queue still leaves the rear pointer pointing to ’b. This is because the implementation of delete-queue! doesn’t bother to clear the rear pointer, knowing that the emptiness of the queue is checked by only using the front pointer. This is reasonable, although it will have consequences for garbage collection.
However, printing the queue as a list is actually easy, since the items in the queue are connected to each other in a list structure. All you have to do is print the list starting from the front pointer.
(define (print-queue queue) (display (car queue)) (newline))
It would perhaps be more useful to return the queue, since this might be useful for other purposes and the REPL will print the result anyway, but this is completely trivial (even more than the above was).