Returning a lambda function in clisp, then evaluating it

Suppose I have this wonderful foo function

[92]> (defun foo () (lambda() 42))
FOO
[93]> (foo)
#<FUNCTION :LAMBDA NIL 42>
[94]> 

Now suppose I want to use foo and return 42.

How can I do it? I searched Google and I cannot come up with the correct syntax.

+5
source share
4 answers

You need a function FUNCALL:

* (defun foo () (lambda () 42))
FOO
* (funcall (foo))
42
+11
source

The relevant terms are: "Lisp -1" and "Lisp -2".

Your call attempt will work in Lisp -1, for example, for example. Scheme or Clojure. The usual Lisp is Lisp -2, but this roughly means that the variable names and function names are separate.

, , , funcall, apply, foo, .

, /, , ( , funcall/apply.

, , , , :

CL-USER> (setf (symbol-function 'foo) (lambda () 42))
#<FUNCTION (LAMBDA ()) {C43DCFD}>
CL-USER> (foo)
42

labels flet ( ) - ( ).

, :

(flet ((foo () 
         42))
  (foo))

. foo , 42. (foo) .

+6

Your function fooreturns function . Use the function funcallto apply the function to the arguments, even if the argument set is empty.

Here you can see that it fooreturns a value of type function:

CL-USER> (let ((f (foo)))
           (type-of f))
FUNCTION
CL-USER> (let ((f (foo)))
           (funcall f))
42
CL-USER> (type-of (foo))
FUNCTION
CL-USER> (funcall (foo))
42
+2
source

Another option besides FUNCALL is APPLY:

(apply (foo) nil)

FUNCALL is the idiomatic path here, but you'll need APPLY when you have a list of options.

+2
source

All Articles