List 球拍/方案-根据位置替换列表中的元素

List 球拍/方案-根据位置替换列表中的元素,list,append,scheme,racket,List,Append,Scheme,Racket,我试图定义一个替换过程,它基本上与列表集做相同的事情。 这是我目前的代码: (define replace (lambda (s pos lst fin-lst) (cond ((zero? pos) (cons (cons (reverse fin-lst) s) (rest lst))) (else (replace s (- pos 1) (rest lst) (cons (first lst) fin-lst)))))) 它有点像它应该做的,但我正在

我试图定义一个替换过程,它基本上与列表集做相同的事情。 这是我目前的代码:

(define replace
  (lambda (s pos lst fin-lst)
    (cond
      ((zero? pos) (cons (cons (reverse fin-lst) s) (rest lst)))
      (else (replace s (- pos 1) (rest lst) (cons (first lst) fin-lst))))))
它有点像它应该做的,但我正在努力让输出看起来像我想要的那样。例如,这就是我想要的结果

(replace 'a 2 '(1 2 3 4 5) '()) => '(1 2 a 4 5)
但到目前为止,这是我的程序返回的结果

'(((1 2) . a) 4 5)

我知道这是由于cons和append的关系,但是我怎样才能修改代码来去掉额外的括号和

你差点就成功了!
reverse
调用放错了位置,您需要使用
append
将两个列表粘在一起。这就是我的意思:

(define replace
  (lambda (s pos lst fin-lst)
    (cond
      ((zero? pos)
       (append (reverse (cons s fin-lst)) (rest lst)))
      (else
       (replace s (- pos 1) (rest lst) (cons (first lst) fin-lst))))))
它的工作原理与您预期的一样:

(replace 'a 2 '(1 2 3 4 5) '())
=> '(1 2 a 4 5)
试试这个:

(define replace
  (lambda (l pos e)
    ((lambda (s) (s s l pos (lambda(x) x)))
     (lambda (s l i col)
       (if (null? l)
           (col '())
           (if (zero? i)
               (col (cons e (cdr l)))
               (s s (cdr l) (- i 1)
                  (lambda (r)
                    (col (cons (car l) r))))))))))


(replace '(a b c d e f) 2 'x)
(replace '(a b c d e f) 0 'x)
(replace '(a b c d e f) 20 'x)