using set! to change the value of a variable in dr

2019-07-27 11:52发布

问题:

I'm trying to delete an occurrence of some value in a binary search tree. This is what I have so far:

(define removeBin (lambda (x t)
       (cond ((< x (car t)) (removeBin x (cadr t)))
             ((> x (car t)) (removeBin x (caddr t)))
             ((equal? x (car t)) 
                   (if(and (null? (cadr t)) (null? (caddr t))) '()
                (let ((r (replacement t))) ((set! (car t) r) (removeBin r t)))))))) 

It's giving me the following error: set!: not an identifier in: (car t) What does that mean? and how can I fix it so that set! would work?

thank you

回答1:

As the error message explains, (car t) is not a valid identifier, and thus its value cannot be changed.

You need to use set-car! like this:

(set-car! t r)

This changes the car of t to r.



回答2:

In Racket there are "mutable pairs" that you get with mcons, access with mcar and mcdr, and mutate with set-mcar! and set-mcdr!. You can get them using the conventional names if you're using one of the standard scheme languages, for example, by starting your code with #lang r5rs.



标签: scheme racket