如何使用递归在Scheme中可视化地堆叠基本块?

时间:2013-09-15 20:32:19

标签: recursion stack scheme

我正在尝试使用递归来堆叠我创建的基本块(y),x次高。

(define stack-copies-of
(lambda (x y)
  (cond
    ((= x 0) 0)
    ((> x 0) (stack y y)

我没有再深入了,因为......我很难过。我希望屏幕上显示一叠块。谢谢!

2 个答案:

答案 0 :(得分:0)

首先,您没有使用递归。 stack-copies-of不是stack。 您需要查看基本列表操作。下面是一些列表:

;; easiest version, looks most like the one you started with
(define (make-list num-elements)
  (if (zero? num-elements)
      '() ; the tail of the list is the empty list
      (cons '* (make-list (- num-elements 1)))))

;; tail recursive version using auxillary procedure
(define (make-list num-elements)
  ;; we define a local auxillary procedure to do the work
  (define (make-list-aux num-elements acc)
    (if (zero? n)
        acc ; return the produced list
        (make-list-aux (- n 1) 
                       (cons '* acc))))
  ;; fire it off
  (make-list-aux num-elements '()))

;; exactly the same as the previous, but with a named let
(define (make-list num-elements)
  ;; a named let can be called by name as a procedure, creating a loop
  (let make-list-aux ((num-elements num-elements)
                      (acc '()))
    (if (zero? n)
        acc
        (make-list-aux (- n 1)
                       (cons '* acc)))))

(display (make-list 10)) ; print the result

我希望你所追求的是基于其中的一个,除了'*你使用额外的论据。

答案 1 :(得分:0)

如果你的数据结构是一个堆栈,你可以定义它,相关的操作是push,pop和one来显示堆栈。

(define stack '())

(define (push e)
  (set! stack (cons e stack)))

(define (pop)
  (let ((e (car stack)))
    (set! stack (cdr stack))
    e))

(define (display-stack)
  (for-each
   (lambda (e) (display e) (newline))
   stack))

以下是堆叠n次元素的递归函数

(define (stack-ntimes n e)
    (when (> n 0)
      (push e)
      (stack-ntimes (- n 1) e)))