1

我在努力推!通过将向量大小加倍并将旧堆栈元素复制到其中,将其复制到完整堆栈上。但是,我的代码目前在无限循环中运行。我究竟做错了什么?

(define push!
    (lambda (ra-stack item)
      (if (<= (vector-length (cells ra-stack))
              (height ra-stack))
          (begin (display "Enlarging stack...")
                 (enlarge-stack! ra-stack)
                 (push! ra-stack item))
          (begin (vector-set! (cells ra-stack) (height ra-stack) item) 
                 (set-height! ra-stack (+ (height ra-stack) 1)) ra-stack))))

  (define enlarge-stack!
    (lambda (ra-stack)
      (let ((cells-length (vector-length (cells ra-stack))))
        (make-vector (* 2 cells-length)))))

下面的所有代码都可以正常工作。

(define set-height! 
    (lambda (ra-stack new-height)
      (vector-set! ra-stack 0 new-height)))

(define cells  
    (lambda (ra-stack)
      (vector-ref ra-stack 1)))

(define height
    (lambda (ra-stack)
      (vector-ref ra-stack 0)))

(define set-cells!  
    (lambda (ra-stack new-cells)
      (vector-set! ra-stack 1 new-cells)))

谢谢!

4

1 回答 1

1

enlarge-stack!不会以任何方式影响它的论点。它不会将set-cells!其单元格添加到新的放大向量中;它也不会尝试将元素从旧向量复制到新向量。

您目前拥有的更恰当地称为enlarged-stack-cells. 即它返回新的、放大的、空的向量,准备好接收旧值的副本。

(define enlarged-stack-cells
    (lambda (ra-stack)
      (let ((cells-length (vector-length (cells ra-stack))))
        (make-vector (* 2 cells-length)))))     ; returns the new vector

(define enlarge-stack!
    (lambda (ra-stack)
      (let ((cs (enlarged-stack-cells ra-stack)))
        (begin
          (copy-cells! cs (cells ra-stack))     ; write it
          (set-cells! ra-stack cs)))))

写下来:

(define copy-cells!
    (lambda (newcells oldcells)
      (let ((cells-length (vector-length oldcells)))
         ....
于 2013-11-14T08:02:17.800 回答