我对 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。
关于string - 在 Racket 中是否有一种简单的方法将字符串转换为变量名称(标识符)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39056589/