0

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?

user16655
  • 1,901
  • 6
  • 36
  • 60

2 Answers2

0

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))))))
Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

Here are two versions:

; list-insert : value index list -> list
;   return list where the ith element is x
(define (list-insert x i xs)
  (if (= i 0)
      (cons x xs)
      (cons (first xs) (list-insert x (- i 1) (rest xs)))))

(define (list-insert/version2 x i xs)
  (define-values (before after) (split-at xs i))
  (append before (list x) after))

(list-insert/version2 'x 2 '(a b c d))
(list-insert          'x 2 '(a b c d))

Both versions will allocate a new list. For large lists it will become inefficient.

soegaard
  • 30,661
  • 4
  • 57
  • 106