Recursion 如何替换列表中特定位置的元素?
我想替换列表中特定位置的元素。到目前为止,我有:Recursion 如何替换列表中特定位置的元素?,recursion,functional-programming,scheme,racket,Recursion,Functional Programming,Scheme,Racket,我想替换列表中特定位置的元素。到目前为止,我有: (define alon (list 1 2 3 4 5 6 7 8 9 10)) (define pos (list 3 6 9)) ;; list with positions to be replaced (define insert (list "a" "b" "c")) ;;replacement (define (list-insert xalon xpos xins counter) (cond ((empty? xi
(define alon (list 1 2 3 4 5 6 7 8 9 10))
(define pos (list 3 6 9)) ;; list with positions to be replaced
(define insert (list "a" "b" "c")) ;;replacement
(define (list-insert xalon xpos xins counter)
(cond
((empty? xins) (cons (rest xalon) '()))
((= counter (first pos))
(cons (first xins) (list-insert (rest xalon) (rest xpos) (rest xins)
(add1 counter))))
(else
(cons (first xalon) (list-insert (rest xalon) xpos xins (add1 counter))))))
当我执行(list insert alon pos inserted 1)
时,我首先得到一个错误:需要一个非空列表;给定:“()
我想我的问题是当(=计数器(第一个位置))
为真时,我再次调用列表插入
,它不会执行(rest xpos)
,因此我得到相同的位置列表,但计数器递增,我得到的是空列表,因此出现错误
我想除了我说的(rest xpos)
之外,一切都正常,(=计数器(第一个pos))
为真时,我调用列表插入
我到底做错了什么,如何解决这个问题,是否有一种更简单的方法可以通过lambda在学生中间阶段实施这个问题
谢谢您的帮助。将(=计数器(第一个pos)
替换为(=计数器(第一个XPO)
:
将(=计数器(第一个pos)
替换为(=计数器(第一个XPO)
:
(define (list-insert xalon xpos xins counter)
(cond
((empty? xins) (rest xalon)) ; no need to cons with '()
((empty? xalon) null) ; makes sense to check for empty xalon also
((= counter (first xpos)) ; xpos, not pos
(cons (first xins)
(list-insert (rest xalon)
(rest xpos)
(rest xins)
(add1 counter))))
(else
(cons (first xalon)
(list-insert (rest xalon)
xpos
xins
(add1 counter))))))