在方案中,如何将一个元素添加到列表中一定次数?

时间:2013-09-26 21:24:02

标签: list scheme racket list-manipulation

所以该函数将3个元素作为数字项和列表。我想把这个项目添加到列表中,如果我这样做了多少次,那么如果我这样做(pad-front 3'a'(b c))它将返回(a a a b c)作为列表。我想我会想把这个项目列入清单,然后就这样做了n次,我只是不确定如何让它去做。

1 个答案:

答案 0 :(得分:1)

在Racket中,使用内置程序很容易:

(define (pad-front n x lst)
  (append                   ; append together both lists
   (build-list n (const x)) ; create a list with n repetitions of x
   lst))                    ; the list at the tail

(pad-front 3 'a '(b c))
=> '(a a a b c)

...但我想你想从头开始实现它。这个想法与上面的相同,但只使用原始程序;我会给你一些提示,以便你弄清楚细节。填写空白:

(define (pad-front n x lst)
  (if <???>            ; base case: if `n` is zero
      <???>            ; then return the tail list
      (cons <???>      ; else cons the element to be repeated
            (pad-front ; and advance the recursion
             <???>     ; subtract one unit from `n`
             x lst)))) ; pass along `x` and `lst`

请注意,诀窍是不断添加x元素,直到不再需要重复(换句话说:直到n为零)。那时,我们只是把尾部列表贴在最后,我们就完成了!

相关问题