Calling the Scheme function using its name from the list

Is it possible to call the Scheme function using only the function name, which is available as a string in the list?

Example

(define (somefunc xy) (+ (* 2 (expt x 2)) (* 3 y) 1)) (define func-names (list "somefunc")) 

And then call somefunc with (car func-names) .

+6
source share
1 answer

In many schema implementations, you can use the eval function:

 ((eval (string->symbol (car func-names))) arg1 arg2 ...) 

However, you do not want to do this at all. If possible, put the functions in a list and call them:

 (define funcs (list somefunc ...)) ;; Then: ((car funcs) arg1 arg2 ...) 

Adding

As commentators noted, if you really want to map strings to functions, you need to do it manually. Since a function is an object like any other, you can simply create a dictionary for this purpose, such as a list of associations or a hash table. For instance:

 (define (f1 xy) (+ (* 2 (expt x 2)) (* 3 y) 1)) (define (f2 xy) (+ (* xy) 1)) (define named-functions (list (cons "one" f1) (cons "two" f2) (cons "three" (lambda (xy) (/ (f1 xy) (f2 xy)))) (cons "plus" +))) (define (name->function name) (let ((p (assoc name named-functions))) (if p (cdr p) (error "Function not found")))) ;; Use it like this: ((name->function "three") 4 5) 
+13
source

Source: https://habr.com/ru/post/894412/


All Articles