tuscland
tuscland

Reputation: 856

How is it possible to call a locally defined function from its symbol?

According to the CLHS, FUNCALL argument is a function designator, which can be a symbol denoting a function defined in the global environment. I am looking for a way to do this locally, like in this example:

(defun test ()
  (let ((name 'local-function))
    (flet ((local-function ()
             'hello))
      (funcall name))))

I am looking for a way to get the function definition from the local environment. Is it possible with Common Lisp?

Upvotes: 2

Views: 519

Answers (2)

Joshua Taylor
Joshua Taylor

Reputation: 85863

If you're just trying to call a local function using funcall, note that a function designator can also be the function object, and you can get that by using the (function name) == #'name notation. I.e., you can do:

(defun test ()
  (flet ((local-function ()
           'hello))
    (funcall #'local-function)))

You can return this value, too, and so let the local function “escape” outside. E.g., you could implement a counter:

(defun make-counter (init)
  (flet ((counter ()
           (incf init)))
    #'counter))

; This case is simple, and could have been:
;
; (defun make-counter (init) 
;   (lambda ()
;     (incf init)))
(let ((counter (make-counter 3)))
  (list (funcall counter)
        (funcall counter)
        (funcall counter)))
;=> (4 5 6)

As uselpa pointed out though, you won't be able to get the function object via a symbol, much in the same way that there's no association at runtime between the symbol named "X" and the lexical variable x in

(let ((x 'foo))
  x)

The lexical variables don't have any association at run time with the symbols that named them in the source code.

Upvotes: 6

uselpa
uselpa

Reputation: 18917

According to this, no. It doesn't work with eval either. I suppose that at run-time there is no trace left of the local function's name.

Also, my understanding is that if the function designator is a symbol, then symbol-function is used, which is not defined for local functions.

Upvotes: 1

Related Questions