首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用球拍实现扩展功能

用球拍实现扩展功能
EN

Stack Overflow用户
提问于 2012-10-04 06:19:51
回答 2查看 496关注 0票数 1

我似乎想不出怎么写这个函数。我正在尝试编写的是一个函数expand,它接受一个列表lst作为'(a (2 b) (3 c))形式的参数,并被计算为'(a b b c c c)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-10-04 07:25:53

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

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

代码语言:javascript
复制
; 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
票数 3
EN

Stack Overflow用户

发布于 2017-08-24 08:20:28

因为这个问题是在三年前回答的,所以我不认为我是在帮助做作业。我只想指出,这两个函数真的不能互相递归( need )。由于replicate是一个相当常见的函数,因此我建议:

代码语言:javascript
复制
(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)))))))

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

代码语言:javascript
复制
(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)))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12717701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档