0
所以這個函數需要3個元素一個數字項和一個列表。我想將這個項目添加到列表中,如果我這麼做的話,這個數字會多少次(pad-front 3'a'(b c)),它會返回(a a b c)作爲列表。我想我會把這個項目列入清單,只是做了n次,我只是不確定如何去做。在方案中,你如何將一個元素添加到列表中一定次數?
所以這個函數需要3個元素一個數字項和一個列表。我想將這個項目添加到列表中,如果我這麼做的話,這個數字會多少次(pad-front 3'a'(b c)),它會返回(a a b c)作爲列表。我想我會把這個項目列入清單,只是做了n次,我只是不確定如何去做。在方案中,你如何將一個元素添加到列表中一定次數?
球拍,這是很容易使用內置的程序:
(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
爲零)。在那一點上,我們只是把尾部列表放在最後,我們就完成了!
非常感謝你以前我在想什麼但謝謝你。 –