[plt-scheme] Problem with set!

From: Cristiano Rocha (lionht14 at gmail.com)
Date: Sat Nov 8 17:32:19 EST 2008


I'm trying to do a procedure called list-set! that receives a list, an
element and a position and inserts the element in the position pos of
the list. The procedure must be destructive because its purpose is to
change an existing list. I'm lists to create a matrix.

I have this

(define (list-set! lst pos elm)
    (set! lst (insert elm pos lst)))

(define (insert elm pos lst)
  (if (= pos 0)
      (cons elm lst)
      (if (null? lst)
          (error "out-of-reach")
          (cons lst (insert elm (- pos 1) lst)))))

(define (new-list)

I do this:

> (define lst (new-list))
> (list-set! lst 0 0)
> lst

and it always returns an empty list.

But if I do this instead:

> (define lst (new-list))
> (set! lst (insert 0 0 lst))
> (set! lst (insert 1 1 lst))
(1 0)

I was wondering if anyone could help me out here because I don't know
what else to do.

Posted on the users mailing list.