Racket: get the value of a variable whose name is stored in another variable

I have a variable "name" whose value is the name of another variable. For example:

(define name 'a)
(define a 1)

      

Then I would like to do something like this:

(set! ,name 10)

      

But this results in an error, so I would like the "name" to be replaced with a value (ie "a"). Thus, the above code sets the value of the variable "a" to 10 and that the variable "name" remains unchanged.

I know I can do it like this:

(eval `(set! ,name 10))

      

But this only works if the variable contained in "name" is a global variable, which is not in my program.

I currently solved the problem by introducing a new namespace, but that makes the code a bit ugly, so I would avoid using eval (and therefore also not introducing a new namespace).

If I'm not mistaken in C ++, this will be done by dereferencing the handle (pointer to pointer).

+3


source to share


1 answer


The reason it (eval `(set! ,name 10))

doesn't work is because there are no local variable names at runtime. Local variables are stored on the stack, so references and assignments to local variables are compiled to "get the value in i'th (counted from the top of the stack)" and "store that value in the ith slot on the stack".

Module level variables are stored in a namespace, so you can use a solution for them eval

.

So what to do with local variables? It would be better to use a hash table instead, but if you really need it, do something like this:



(define (set-local-variable name val)
  (match name
    ['a (set! a val)]
    ['b (set! b val)]
    ...))

      

where a, b, ... are local variables. Of course, you need to place the definition within the scope of the local variables in question. This also implies that you need to define set-local-variable

for each area.

This quickly becomes a pain to maintain, so look for an alternative solution - like one based on hash tables.

+3


source







All Articles