首页 > 解决方案 > Racket/Scheme - 根据位置替换列表中的元素

问题描述

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

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

我知道这是由于缺点与附加,但我怎样才能更改我的代码以摆脱额外的括号和 . ?

标签: listappendschemeracket

解决方案


你几乎拥有它!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)

推荐阅读