Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Scheme function using its name from a list

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

Example

(define (somefunc x y)
  (+ (* 2 (expt x 2)) (* 3 y) 1))

(define func-names (list "somefunc"))

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

like image 745
commsoftinc Avatar asked Aug 05 '11 19:08

commsoftinc


1 Answers

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

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

You generally don't really want to do that, however. If possible, put the functions themselves into the list and call them:

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

Addendum

As the commenters have pointed out, if you actually want to map strings to functions, you need to do that manually. Since a function is an object like any other, you can simply build a dictionary for this purpose, such as an association list or a hash table. For example:

(define (f1 x y)
  (+ (* 2 (expt x 2)) (* 3 y) 1))
(define (f2 x y)
  (+ (* x y) 1))

(define named-functions
  (list (cons "one"   f1)
        (cons "two"   f2)
        (cons "three" (lambda (x y) (/ (f1 x y) (f2 x y))))
        (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)
like image 194
Matthias Benkard Avatar answered Nov 08 '22 19:11

Matthias Benkard