用球拍实现扩展功能



我似乎不知道如何编写这个函数。我正在尝试编写的是一个函数expand,它将列表lst作为形式'(a (2 b) (3 c))的参数,并被计算为'(a b b c c c)<</p>

div class="ans>

这看起来像家庭作业,所以我不会给你一个直接的答案。相反,我会给你一些正确方向的指示。最有用的提示是,您应该将问题拆分为两个过程,一个用于处理"外部"列表,另一个用于生成内部子列表中编码的重复项。

请注意,这两个过程是相互递归的(例如,它们相互调用)。expand过程在列表中重复,而repeat过程在重复次数上重复。这是所提出的解决方案的一般结构,填空:

; input:  lst - list to be processed
; output: list in the format requested
(define (expand lst)
  (cond ((null? lst)             ; if the list is null
         '())                    ; then return null
        ((not (pair? (car lst))) ; if the first element of the list is an atom
         (cons <???> <???>))     ; cons the atom and advance the recursion
        (else                    ; if the first element of the list is a list
         <???>)))                ; call `repeat` with the right params

; input: n   - number of repetitions for the first element in the list
;        lst - list, its first element is of the form (number atom)
; output: n repetitions of the atom in the first element of lst
(define (repeat n lst)
  (if (zero? n)          ; if the number of repetitions is zero
      (expand (cdr lst)) ; continue with expand's recursion
      (cons <???>        ; else cons the atom in the first element and
            <???>)))     ; advance the recursion with one less repetition

由于这是三年前回答的,我不认为我在帮助家庭作业。只想指出,这两个函数真的need不是相互递归的。由于replicate是一个相当常见的函数,我建议:

(define (replicate what n)
  (if (zero? n)
      (list)
      (cons what (replicate what (- n 1)))))
(define (my-expand xs)
  (if (empty? xs)
      (list)
      (let ((x (first xs)))
        (if (list? x)
            (let ((the-number (first x))
                  (the-symbol (cadr x)))
              (flatten (cons (replicate the-symbol the-number)
                    (my-expand (rest xs)))))
            (cons x (my-expand (rest xs)))))))

当然,最好使用两个列表并在最后执行平展,如下所示:

(define (my-expand xs)
  (define (inner-expander xs ys)
    (if (empty? xs) (flatten (reverse ys))
        (let ((x (first xs)))
        (if (list? x)
            (let ((the-number (first x))
                  (the-symbol (cadr x)))
              (inner-expander (rest xs) (cons (replicate the-symbol the-number) ys)))                    
            (inner-expander (rest xs) (cons x ys))))))
  (inner-expander xs (list)))

最新更新