Page 1 of 1

Creating functions from strings

Posted: Sat May 24, 2008 3:23 pm
by cormullion
Is there a way to create a function definition if you have the body as a string?

Eg

Code: Select all

(set 'body "(println x) (exit)")
(define (func) body)

Posted: Sat May 24, 2008 4:00 pm
by rickyboy
Hey cormullion,

I don't know exactly what you're driving at, but does this help?

Code: Select all

(define (string2func str func-name)
  (eval-string (string "(define (" func-name ") " str ")")))

(set 'x 42)
(set 'body "(println \"Hello\") (println x)")

> (string2func body 'func)
(lambda () (println "Hello") (println x))
> (func)
Hello
42
42

Posted: Sat May 24, 2008 5:14 pm
by cormullion
Ah, yes - I was thinking about list and string. I must have forgotten that eval-string doesn't always run immediately...

Thanks! Glad you haven't gone over to Arc completely, Ricky!

Posted: Sat May 24, 2008 5:53 pm
by rickyboy
cormullion wrote:Glad you haven't gone over to Arc completely, Ricky!
:-)