How to replace an element in a specific position of a list?

空扰寡人 提交于 2019-12-11 04:15:25

问题


I want to replace an element in a specific position of a list. I have this so far:

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

When I do (list-insert alon pos inserted 1) I get an error first: expects a non-empty list; given: '() I think my problem is when (= counter (first pos)) is true and I call list-insert again it doesn't do (rest xpos) so I end up with the same list of positions but the counter increments and I end up with the empty list thus the error.

I think everything works except of like I said (rest xpos) when (= counter (first pos)) is true and I call list-insert.

What exactly do I do wrong, how do I fix this and is there an easier way to implement this on the intermidiate student level with lambda?

Thank you for your help.


回答1:


Replace (= counter (first pos) with (= 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))))))


来源:https://stackoverflow.com/questions/47441943/how-to-replace-an-element-in-a-specific-position-of-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!