I am trying to implement a procedure in Scheme that will add an element x
at position i
to an existing list. This is what I came up with:
(define empty-list '())
(define (add i x L)
(cond ((null? L) (set! L (list x)))
((= i 0)(set! L (cons x L)))
(else (set! L (cons (car L)
(add (- i 1) x (cdr L))))
)))
(add 0 1 empty-list) -> returns ()
(add 1 2 empty-list) -> returns ()
(add 2 3 empty-list) -> returns ()
The code doesn't update the existing list. However, if I just run
(set! empty-list (list 1))
or
(set! empty-list (cons 2 empty-list))
it works fine.
I am struggling to understand what I am doing wrong.