1

我似乎无法弄清楚如何编写这个函数。我正在尝试编写的是一个函数expand,它将列表lst作为表单的参数'(a (2 b) (3 c))并被评估为'(a b b c c c)

4

2 回答 2

3

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

请注意,这两个过程是相互递归的(例如,它们相互调用)。该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
于 2012-10-03T23:25:53.053 回答
0

正如三年前回答的那样,我不认为我在帮助做作业。只想指出,这两个函数真的不是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)))
于 2017-08-24T00:20:28.217 回答