简体   繁体   English

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

[英]In scheme how do you add an element to a list a certain number of times?

so the function would take 3 elements a number item and a list. 因此该函数将使用3个元素(一个数字项和一个列表)。 I want to add the item to the list how ever many times the number says so if i did (pad-front 3 'a '(bc)) it would return (aaabc) as the list. 我想将项目添加到列表中,数字会说多少次,所以如果我这样做了(pad-front 3'a'(bc)),它将返回(aaabc)作为列表。 I think i would want to cons the item to the list and just do that n times im just not sure on how to get it to do it. 我想我想把这个项目限制在列表中,只是不知道如何使它完成就做n次。

In Racket this is easy using built-in procedures: 在球拍中,使用内置过程很容易:

(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)

... But I guess you want to implement it from scratch. ...但是我想您想从头开始实现它。 The idea is the same as above, but using only primitive procedures; 这个想法与上面相同,只是使用原始过程。 I'll give you some hints so you can figure out the details. 我会给您一些提示,以便您了解详细信息。 Fill-in the blanks: 填写空白:

(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`

Notice that the trick is to keep adding the x element until no more repetitions are needed (in other words: until n is zero). 注意,诀窍是继续添加x元素,直到不再需要重复为止(换句话说:直到n为零)。 At that point, we just stick the tail list at the end, and we're done! 到那时,我们只需将尾部列表放在最后,就可以了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM