0

Consider the following code

(defun somefunc (text) (message "hello, somefunc called with %s" text) ) (defun func-caller (func) (func "some string") ) (func-caller 'somefunc) 

This results in Lisp error: (void-function func) because inside func-caller the local symbol func has its variable component, not its function component, set to somefunc which is why we would have to write (funcall func "some string") instead.

Is there any way to tweak func-caller such that the parameter func is usable as a function rather than a variable in the body of func-caller?

I know I could do (funcall func ...) but the funcall is what I would like to avoid. Any trick to make the func behave like a function symbol, other than it being globally defined would be nice.

Why would I want this? No specific reason other than curiosity and to understand the inner workings of elisp better.

3
  • 3
    This question is similar to: How to call a function that is the value of a variable?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Dec 12, 2024 at 20:52
  • I did edit the question to make clear that I know about funcall and that funcall is exactly what I would like to avoid. Commented Dec 15, 2024 at 14:13
  • The question is: why do you want to avoid it? Commented Dec 16, 2024 at 2:08

3 Answers 3

1

No; your question covers the implementation details that make Emacs Lisp a Lisp-2 rather than a Lisp-1, and it has no support for doing what you've asked, short of something like:

(defun func-caller (func) (cl-flet ((func (&rest args) (apply func args))) (func "some string"))) 

But there's unlikely to be any good reason to do that when you can simply funcall or apply directly.

0

Yea, just write (funcall func …) instead.

0

Finally I found one more reason why it is not possible to do what I want to do in a simple way. It is in the manual saying about "forms":

The first element is not evaluated, as it would be in some Lisp dialects such as Scheme.

So through whichever hoops we jump, a form like (f args) will never look at the value-as-variable of f to find the function to call.

Now you could still think you could bind the function cell of symbol f to a function in a scoped way, similar like let and setq allow scoping (dynamic or lexical). But the difference seems to be that, when reading up set it talks about binding scopes, yet fset does not.

Yet in principle I think it could work by writing a macro which uses cl-flet such that a function

(defun booo (arg1 arg2) body) 

is basically converted to something having a body like

(cl-flet ((arg1 arg1) (arg2 arg2)) body) 

But looking at what cl-flet makes of it, replacing uses of arg1 basically with funcall arg1, I rather don't try.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.