Search code examples
schemesymbolsevaluationguile

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


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.


Solution

  • 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