Reputation: 506
I'm trying to create a lambda from parameters such that (apply (make-lambda '(a b) '(+ a b)) '(1 2))
returns 3
My first attempt (define (make-lambda params func) (lambda params func))
returns (+ a b)
This code works but it doesn't feel right to me: (define (make-lambda params func) (eval (list 'lambda params func)))
What is the correct way of doing this?
Upvotes: 1
Views: 86
Reputation: 117350
Because I am bored, and if your scheme supports syntax-case
:)
(define-syntax make-lambda
(lambda (x)
(syntax-case x (quote)
[(_ (quote pars) (quote body))
#'(lambda pars body)])))
PS: Will probably work with syntax-rules
too (see Óscar López's answer). So I am lazy too.
Example: http://eval.ironscheme.net/?id=186
Here is a syntax-rules
version:
(define-syntax make-lambda
(syntax-rules (quote)
[(_ (quote pars) (quote body))
(lambda pars body)]))
Example: http://eval.ironscheme.net/?id=187
Note: keep in mind, this is exactly what you asking for :D
Upvotes: 1
Reputation: 236150
You have to evaluate the list to use it as a procedure, otherwise is just a list of data which happens to have the symbol lambda
as the first element. This syntax is a bit simpler, but is essentially the same:
(define (make-lambda params func)
(eval `(lambda ,params ,func)))
This should work:
(apply (make-lambda '(a b) '(+ a b)) '(1 2))
=> 3
Alternatively, using a macro as suggested by Leppie:
(define-syntax make-lambda
(syntax-rules ()
((_ args body)
(lambda args body))))
Use it like this:
(apply (make-lambda (a b) (+ a b)) '(1 2))
=> 3
Upvotes: 3