Question

I have a list like that -> (define l '(at1 at2 at3)) where at1 is the name of a function. When I try to put that value as the name of a function (i.e. (at1 value1 value2)), I obtain this:

application: not a procedure; expected a procedure that can be applied to arguments

because at1 is a list ('valueofat1). I'm trying to use apply and list->string, but both aren't work. What am I doing wrong? How can I use the value of a list in a given position as a function?

Was it helpful?

Solution

If you definitely want to use a list of symbols representing function names you can use apply and eval, but beware: eval is evil and you should avoid using it!

; 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

The above will return 42. I have the feeling that you're struggling with an XY problem, what are you really trying to accomplish? wouldn't it be a better idea to use a list of functions instead of a list of symbols representing function names? I mean, like this:

; 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top