sicp-ex-3.21



<< Previous exercise (3.21) | Index | Next exercise (3.22) >>


meteorgan

  
  
 (define (print-queue queue) (car queue)) 

Shawn

The exercise asks us to print the queue, not return the queue. Also, we should use procedures like front-ptr instead of car. Here is my solution:

 (define (print-queue q) 
   (define (iter x) 
     (if (null? x) 
         (newline) 
         (begin (display (car x)) 
                (iter (cdr x))))) 
   (iter (front-ptr q))) 

Indeed, it does ask to print, but at the end we are still printing values even if we don't explicitly invoke 'display'. You can print (+ 3 3) directly into the interpreter without a call doing (display (+ 3 3)); doing display is actually worse, it gives you ugly text like "unspecified return value" when it's done. Also, we are not 'copying' the whole queue, we are just returning a pointer, a 'cons', and we delegate the job of printing to the interpreter. So it's probably more efficient than calling display.

Why do you think the every queue-mutator function (in the authors' code) returns the (pointer to) queue when it's done? It's for printing the queue, or what the interpreter thinks is the representation of the queue. But us users, we don't want the explicit list structure that the queue is implemented in to be displayed. Instead of returning the (pointer to) queue we can just return (print-queue queue) in each of the functions like (insert-queue!) and (delete-queue!), that will keep bitdiddle happy



  
 (define (print-queue queue) (map display (front-ptr queue))) 

>>>