Is it possible to implement `apply` in Lisp with` eval`?

I am learning Racket (similar to the Lisp scheme) and I tried to do something like (apply + '(1 2)) , but without using apply , and I failed. I was pretty sure that apply can be modeled somehow with eval , but now I have doubts.

So my question is: can apply be implemented in Racket (or another Lisp) using only eval and other basic operations? That is how to make this work:

 { define [my-apply f arg] ;; what does go here? } (my-apply + (list 1 2)) ; => 3 
+4
source share
2 answers

Sure.

 (defun my-apply (function arglist) (eval (cons function (mapcar (lambda (x) (list 'quote x)) arglist)))) (my-apply '+ '(1 2 3)) 6 (my-apply '+ '(1 a 3)) *** - +: A is not a number 
  • Please note that you cannot do (my-apply #'+ '(1 2 3)) , this will require an additional step.

  • Note that you need to quote arglist elements to avoid double pricing (thanks to Ryan for that!)

+2
source

I found this one (in Racket):

 { define [my-apply func args] { define ns-for-eval (make-base-namespace) } (eval (cons func args) ns-for-eval) } (my-apply + (list 1 2)) ; => 3 

Is there something wrong with this?

0
source

All Articles