Search code examples
listschemer5rs

Add or remove element in the middle of list (Scheme)


Is it possible to add or remove elements in the middle of a linked list in Scheme? I can't seem to think of a way doing this with car/cdr/cons, but I reccon there must be a way to this.

If I have a list '(1 3 5 6), and I need to put in 4 between 5 and 6 for example, is this doable?


Solution

  • Adding an element at a given position was done in a previous answer. Removing an element at a given position is similar:

    (define (delete-at k lst)
      (cond ((null? lst)
             '())
            ((zero? k)
             (cdr lst))
            (else
             (cons (car lst)
                   (delete-at (sub1 k) (cdr lst))))))