问题
I have railroad1 and station1 defined, and I want to update the value of railroad1 without using set! or another define. For example:
(define railroad1 (list 1991))
(define station1 (list "station"))
(define (add-station railroad station)
(append railroad station)
)
When I call (add-station railroad1 station1) I get
(1991 "station")
Now I could do this:
(define railroad1 (add-station railroad1 station1))
So that railroad1 is now (1991 "station") instead of just (1991).
However, my end goal is to be able to just call
(add-station railroad1 station1)
and have railroad1 be redefined as (1991 "station") without explicitly redefining railroad1 as above, and without using set! either.
EDIT: set-car!, set-cdr!, and other similar special forms are also not allowed.
Is there any way to do this?
回答1:
What if you used a let statement? That way you set the initial values of railroad1 and station1 in the let and then you can update it by calling the let again. Scoping should keep your variables "safe" from set!. I'd love to see more of the code that you've written like this function add-station you're calling in your second line there.
回答2:
Yes, if you're allowed to use set-cdr!
.
(set-cdr! railroad1 station1)
回答3:
This should work:
(define-syntax add-station
(syntax-rules ()
((_ railroad station) (define railroad (append railroad station)))))
EDIT
Sorry, didn't notice the homework tag. I'll explain the answer.
define-syntax
produces what is called a macro. Macros work differently than normal functions. Instead of evaluating the operands, they directly replace the macro call with the macro body. The _
in the syntax-rules
means the original name of the macro, i.e. add-station
. So when you call
(add-station railroad1 station1)
it is directly replaced with
(define railroad1 (append railroad1 station1))
which is then executed.
Hope this helps!
来源:https://stackoverflow.com/questions/5373463/getting-the-effects-of-set-without-using-it