Search code examples
stringracketidentifier

Is there an easy way to convert strings to variable names (identifiers) in Racket?


I am pretty new in Racket and I have tried to do something that is really easy in other languages, such as PHP, which is converting a string to a variable name. Something like:

#lang racket
(define t0 3)
(display t0) ; It outputs 3
(define (symbol? (string->symbol "t1")) 2 )
(display t1) ; It would output 2, however it throws an error :(

Is there a way to convert a string to identifier? Because I need to define variable names from strings, dynamically.


Solution

  • Indeed soegaard hash tables are a very good solution, here is an example:

    #lang racket
    (define ht (make-hash))
    (define sx "x")
    (define sy "y")
    (define sr "r")
    (hash-set! ht sx 2)
    (hash-set! ht sy 3)
    (define r (+ (hash-ref ht sx) (hash-ref ht sy))) ;do calculation (+ 2 3)
    (hash-set! ht sr r)
    (hash-ref ht sr) ; it will output 5