我有一个这样的列表 - > (define l '(at1 at2 at3))
其中at1
是函数的名称。当我尝试将该值作为函数的名称(即(at1 value1 value2)
)时,我得到了这个:
申请:不是程序; 期望一个可以应用于参数的程序
因为at1
是一个列表('valueofat1
)。我尝试使用apply
和list->string
,但两者都不起作用。我究竟做错了什么?如何将给定位置的列表值用作函数?
答案 0 :(得分:0)
如果您肯定想使用代表函数名称的符号列表,可以使用apply
和eval
,但要注意:eval
is evil,您应该避免使用它!
; some functions
(define (at1 x y) (+ x y))
(define (at2 x y) (- x y))
(define (at3 x y) (* x y))
; a list of symbols named like the functions
(define lst '(at1 at2 at3))
; operands
(define value1 30)
(define value2 12)
; obtain evaluation namespace
(define-namespace-anchor a)
(define ns (namespace-anchor->namespace a))
; apply the first function from the list of function names
(apply (eval (car lst) ns) (list value1 value2))
^ ^
evaluate operator list of operands
上述内容将返回42
。我觉得你正在努力解决XY problem,你想要实现什么?使用函数列表而不是表示函数名称的符号列表不是更好的主意吗?我的意思是,像这样:
; some functions
(define (at1 x y) (+ x y))
(define (at2 x y) (- x y))
(define (at3 x y) (* x y))
; a list of functions
(define lst (list at1 at2 at3))
; operands
(define value1 30)
(define value2 12)
; apply the first function from the list of functions
((car lst) value1 value2)
=> 42