2017-11-22 33 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)))))) 
関連する問題