7

是否可以仅使用作为列表中的字符串可用的函数名称来调用 Scheme 函数?

例子

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

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

然后用 调用 somefunc (car func-names)

4

1 回答 1

14

在许多 Scheme 实现中,您可以使用该eval函数:

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

但是,您通常并不想这样做。如果可能,将函数本身放入列表并调用它们:

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

附录

正如评论者所指出的,如果您真的想将字符串映射到函数,则需要手动执行此操作。由于函数与任何其他函数一样都是对象,因此您可以简单地为此目的构建一个字典,例如关联列表或哈希表。例如:

(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)
于 2011-08-05T21:00:58.867 回答