Although you can implement the requested functionality with lists, a natural way to solve this problem is to use vector and remember that in the indexes, schemes start at 0 (so the second argument to vector-set! Is 1 , not a 2 ):
(define thevector (vector 0 1 0 0 7 7 7)) ; thevector is #(0 1 0 0 7 7 7) (vector-set! thevector 1 4) ; thevector is #(0 4 0 0 7 7 7)
Now, if you definitely need to use a list, something like this will work:
(define (set-cell lst idx val) (cond ((null? lst) '()) ((zero? idx) (cons val (cdr lst))) (else (cons (car lst) (set-cell (cdr lst) (sub1 idx) val)))))
And you would call it like this:
(define thelist '(0 1 0 0 7 7 7)) (set-cell thelist 1 4) > (0 4 0 0 7 7 7)
Again, I use 0-based indexing, like convention. Also note that thelist not been changed; instead, set-cell returns a new list with a modification.
source share