How to replace an element in a specific position o

2019-08-15 04:22发布

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条回答
祖国的老花朵
2楼-- · 2019-08-15 04:49

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))))))
查看更多
登录 后发表回答