リスト内の文字列として利用可能な関数名のみを使用してScheme関数を呼び出すことは可能ですか?
例
(define (somefunc x y)
(+ (* 2 (expt x 2)) (* 3 y) 1))
(define func-names (list "somefunc"))
そして、somefunc を で呼び出します(car func-names)。
リスト内の文字列として利用可能な関数名のみを使用してScheme関数を呼び出すことは可能ですか?
(define (somefunc x y)
(+ (* 2 (expt x 2)) (* 3 y) 1))
(define func-names (list "somefunc"))
そして、somefunc を で呼び出します(car func-names)。
eval多くの Scheme 実装では、次の関数を使用できます。
((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)