代码之家  ›  专栏  ›  技术社区  ›  Nime

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

  •  1
  • Nime  · 技术社区  · 8 年前

    我想替换列表中特定位置的元素。到目前为止,我有:

    (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 再说一遍,这也不行 (rest xpos) 因此,我得到了相同的位置列表,但计数器递增,我得到了空列表,从而得到了错误。

    我想除了我说的以外,一切都正常 (其余XPO) 什么时候 (=计数器(第一个位置)) 真的 然后我打电话 .

    我到底做错了什么,我该如何解决这个问题,有没有更简单的方法在中间阶段的学生水平上用lambda实现这一点?

    1 回复  |  直到 8 年前
        1
  •  0
  •   uselpa    8 年前

    代替 (= 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))))))