有没有一种简单的方法可以在 Racket 中将字符串转换为变量名(标识符)?

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

我是 Racket 的新手,我尝试做一些在其他语言中非常容易的事情,例如 PHP,它将字符串转换为变量名。 类似于:

#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 :(

有没有办法将字符串转换为标识符?因为我需要动态地从字符串定义变量名。

可以在命名空间的帮助下做您想做的事。但是,请先查看哈希表。

#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")))

这个程序的输出是42。

确实soegaard哈希表是一个很好的解决方案,这里有一个例子:

#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