【问题标题】:In scheme how do you add an element to a list a certain number of times?在方案中,如何将元素添加到列表中一定次数?
【发布时间】:2013-09-26 21:24:01
【问题描述】:

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

【问题讨论】:

    标签: list scheme racket list-manipulation


    【解决方案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 为零)。到那时,我们只需将尾部列表放在最后,就完成了!

    【讨论】:

    • 非常感谢我之前在想什么,但谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2012-09-25
    • 2015-08-01
    • 2017-04-12
    • 1970-01-01
    • 2019-03-31
    • 2023-01-13
    相关资源
    最近更新 更多