开发者

How can I use a string to reference a symbol?

The following code wi开发者_开发问答ll generate #f and #t

1: (define dict (hash 1 'a 2 'b ))
2: (hash? (string->symbol "dict"))
3: (symbol? (string->symbol "dict"))

Basically, I want the string "dict" will be turned into the hash dict defined in line 1. How can I do that?


The most straightforward way would be to eval the result of string->symbol, like so:

> (define dict 5)
> (eval (string->symbol "dict"))
5

However, getting eval involved is almost never the right thing to do. A much better way to associate strings with values is to use a hashtable as @yi_H suggests:

> (define ht (make-hash))
> (hash-set! ht "dict" 5)
> (hash-ref ht "dict")
5

Update: I missed the [racket] tag initially; the example should now work with #lang racket.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜