I'm writing a Scheme interpreter and I need to be able to create and return a Python function from a string.<br>
<br>
This is a port of another Scheme interpreter I wrote in Scheme. What I'm trying to do looked like this:<br>
<br>
(define (scheme-syntax expr)<br>
(hash-table-set! global-syntax (car expr) (eval (cadr expr))))<br>
<br>
Where expr was of the form (symbol (lambda (exp) ...)). This added a new special form handler.<br>
<br>
I came up with a very ugly solution in Python:<br>
<br>
def add_special_form_handler(expr):<br>
exec(expr.cdr.car)<br>
special_forms[expr.car] = f<br clear="all"><br>
Where expr.car = the symbol to be dispatched on and expr.cdr.car = a
string of Python code defining a function that must be named f.<br>
<br>
I wanted to use an anonymous function here, but with the limitations of
Python's lambda that would probably make things more complicated.
Failing that I wanted to allow the user to manually return the function
from the string, like this:<br>
<br>
a = exec("""<br>
def double(x):<br>
return x * 2<br>
double<br>
""")<br>
<br>
However it seems that exec does not return a value as it produces a SyntaxError whenever I try to assign it. <br>
<br>
Is there a better way to do this?<br>
<br>-- <br>Nick Zarczynski<br><a href="http://pointlessprogramming.wordpress.com" target="_blank">Pointless Programming Blog</a><br><br>