2017-11-22 11 views
0

목록의 특정 위치에있는 요소를 바꾸려고합니다. 지금까지이 있습니다목록의 특정 위치에있는 요소를 대체하는 방법은 무엇입니까?

(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 내가 다시는 (rest xpos)하지 않습니다 list-insert를 호출 할 때 그래서 동일한 목록으로 끝날 위치가 증가하지만 카운터가 증가하고 빈 목록으로 끝납니다. 따라서 오류가 발생합니다.

(= counter (first pos))true이고 내가 list-insert 일 때를 제외하고는 모든 것이 작동한다고 생각합니다.

정확하게 무엇을 잘못 했습니까?이를 해결하고 람다와 함께 중간 수준의 학생 수준에서 이것을 구현하는 더 쉬운 방법이 있습니까?

도움 주셔서 감사합니다.

답변

0

(= counter (first xpos)(= counter (first pos) 교체 :

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