luispcosta
luispcosta

Reputation: 572

Create a lambda function in runtime lisp

Let's say i have a function "create-lambda" defined like this:

(defun create-lambda(x y)
    (lambda(z) (let ((foo (some-other-function z y))) (if (= x foo) T))))

If i call this function, like this:

(create-lambda 2 3)

It will return:

#<FUNCTION :LAMBDA (Z) (LET ((FOO (SOME-OTHER-FUNCTION Z Y))) (IF (= X FOO) T))>

What i want is, to return this:

#<FUNCTION :LAMBDA (Z) (LET ((FOO (SOME-OTHER-FUNCTION Z 3))) (IF (= 2 FOO) T))>

Is this possible?

Upvotes: 0

Views: 91

Answers (1)

Sylwester
Sylwester

Reputation: 48745

It doesn't matter for the end result since x and y are bound in the lexical scope to 2 and 3. You are saying you don't want:

(let ((x 2) (y 3))
  (let ((foo (some-other-function z y))) 
    (if (= x foo) T)))

But you want:

(let ((foo (some-other-function z 3))) 
  (if (= 2 foo) T))

But I can't tell the difference. Can you? Anyway. You can coerce any data structure to be a function like this:

(defun create-lambda (x y)
  (coerce `(lambda(z) 
             (let ((foo (some-other-function z ,y)))
               (when (= ,x foo) T))) 
          'function))

Or you can make create-lambda a macro:

(defmacro create-lambda (x y)
  `(lambda(z) 
     (let ((foo (some-other-function z ,y)))
          (when (= ,x foo) T))))

The differences between these are easy to spot if you call it with side effects(create-lambda (print 3) (print 4)). In the first the side effects will happen right away since functions evaluate all their arguments while the macro will just replace the whole thing for x and y and the side effect happen at call time.

Upvotes: 1

Related Questions