Reputation: 717
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.
Upvotes: 2
Views: 472
Reputation: 717
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
Upvotes: 1
Reputation: 31147
You can do what you want with the help of namespaces. However look into hash tables first.
#lang racket
(define-namespace-anchor here)
(define ns (namespace-anchor->namespace here))
(define foo 42)
(parameterize ([current-namespace ns])
(namespace-variable-value (string->symbol "foo")))
The output of this program is 42.
Upvotes: 2