如何替换列表特定位置的元素?

时间:2017-11-22 18:50:51

标签: 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? 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)时出现错误first: expects a non-empty list; given: '()我认为我的问题出现在(= counter (first pos))true并且我再次致电list-insert时它不会出现问题; t (rest xpos)所以我最终得到相同的位置列表,但计数器递增,我最终得到空列表,因此错误。

我认为除了我(rest xpos) (= counter (first pos)) true list-insert之外我所说的<Label bsStyle='success'>{myNumber}</Label>时,一切正常。

我究竟做错了什么,如何解决这个问题?是否有更简单的方法在lambda的中间学生级别实现这一点?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

(= counter (first pos)替换为(= counter (first xpos)

(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))))))
相关问题