Recursion 如何使用递归在Scheme中直观地堆叠基本块?

Recursion 如何使用递归在Scheme中直观地堆叠基本块?,recursion,stack,scheme,Recursion,Stack,Scheme,我试图使用递归来堆叠我创建的基本块(y),x倍高 (define stack-copies-of (lambda (x y) (cond ((= x 0) 0) ((> x 0) (stack y y) 我没有走得更远,因为。。。我被难住了。我希望块堆栈出现在屏幕上。谢谢大家! 首先,您没有使用递归堆栈副本不是堆栈。 您需要了解基本的列表操作。下面列出一些: ;; easiest version, looks most like the one you started

我试图使用递归来堆叠我创建的基本块(y),x倍高

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

我没有走得更远,因为。。。我被难住了。我希望块堆栈出现在屏幕上。谢谢大家!

首先,您没有使用递归<代码>堆栈副本不是
堆栈
。 您需要了解基本的列表操作。下面列出一些:

;; 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

我希望您所追求的可以基于其中之一,而不是“*您使用额外的参数。

如果您的数据结构是一个堆栈,您可以定义它和相关的操作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)))