[plt-scheme] evaluating contents of a string
On Tue, 25 Jul 2006, David Richards wrote:
> "(lambda () (current-seconds))"
>
> What is the 'best practice', or most elegant way to obtain a scheme
> procedure from the contents of a string?
Hi David,
Is a requirement that we allow arbitrary lambdas, or can something more
restrictive do? We can create a mapping between symbols and function
values:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require (lib "etc.ss"))
;; etc.ss contains the hash-table helper function
(define functions
(hash-table ('square (lambda (x) (* x x)))
('add1 add1)
('double (lambda (x) (* x 2)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
which is a bit more controlled. (This code could be modified to work on
strings instead of symbols.)
Use of any function in this table can still be driven by the user:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
> (let loop ()
(let ([cmd (read)])
(printf "(~a 42) = ~a~n" cmd ((hash-table-get functions cmd) 42))
(loop)))
square
(square 42) = 1764
double
(double 42) = 84
add1
(add1 42) = 43
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Best of wishes!