我似乎想不出怎么写这个函数。我正在尝试编写的是一个函数expand,它接受一个列表lst作为'(a (2 b) (3 c))形式的参数,并被计算为'(a b b c c c)
发布于 2012-10-04 07:25:53
这看起来像家庭作业,所以我不会给你一个直接的答案。相反,我将在正确的方向上给你一些建议。最有用的提示是,您应该将问题分成两个过程,一个用于处理“外部”列表,另一个用于生成内部子列表中编码的重复项。
请注意,这两个过程都是相互递归的(例如,它们相互调用)。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发布于 2017-08-24 08:20:28
因为这个问题是在三年前回答的,所以我不认为我是在帮助做作业。我只想指出,这两个函数真的不能互相递归( 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)))https://stackoverflow.com/questions/12717701
复制相似问题