How do I evaluate a symbol returned from a function in Scheme?

南笙酒味 提交于 2019-12-10 15:47:15

问题


I'm refamiliarizing myself with Scheme and I've hit a problem that is probably reflecting a fundamental misunderstanding on my part.

Say I do the following in Scheme (using Guile in this case but it's the same in Chicken):

> (define x 5)
> x
5
> (string->symbol "x")
x
> (+ 5 (string->symbol "x"))
<unnamed port>:45:0: In procedure #<procedure 1b84960 at <current input>:45:0 ()>:
<unnamed port>:45:0: In procedure +: Wrong type: x
> (symbol? (string->symbol "x"))
#t
> (+ 5 x) ; here x is dereferenced to its value 5
10
> (+ 5 'x) ; here x is not dereferenced
<unnamed port>:47:0: In procedure #<procedure 1c7ba60 at <current input>:47:0 ()>:
<unnamed port>:47:0: In procedure +: Wrong type: x    

I understand that string->symbol is returning a symbol, x, which is effectively quoted. However, I cannot figure out how to use the symbol returned by string->symbol in any later context. How can I have Scheme evaluate that symbol?

To give a background on why I want to do this, it's that I'm writing a C program with embedded Guile. I would like to be able to be able to access symbols defined in Guile by name from C, using for example scm_from_*_symbol or scm_string_to_symbol. The reasons these functions aren't working the way I thought they would is related to my core question above. Perhaps there's a better way to do what I want to do with Guile, but that's a different question. Right now I'm interested in the fundamental question above.


回答1:


You should read the chapter fly-evaluation of the Guile documentation.

You want eval and probably interaction-environment

I recommend reading the famous SICP and Queinnec's Lisp In Small Pieces




回答2:


What you want is to evaluate the symbol (not to "dereference" it). I think this is what you meant:

(define x 5)
(+ 5 (eval 'x (interaction-environment)))
=> 10

Take a look at the documentation for further details.




回答3:


Symbols are not special in this sense, that is they are not easier to evaluate than ordinary strings.

Symbol is much like a string, it just doesn't have quotes around it. Well, the fundamental difference is, of course, not absence of quotes, but the fact that symbols are interned. This means that strings "x" and "x" are two different strings (although they are equal), while symbols 'x and 'x are actually the same object.



来源:https://stackoverflow.com/questions/16873043/how-do-i-evaluate-a-symbol-returned-from-a-function-in-scheme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!