Can someone explain to me why the code below throws an error
(let ((lexical-binding t) (fn (lambda (y) (+ y 4))) (x 4)) (pcase x (10 (- x 2)) (4 (fn x))))
and is there a way to fix it without
defun'ing a function?
Emacs Stack Exchange is a question and answer site for those using, extending or developing Emacs. It only takes a minute to sign up.Sign up to join this community
Emacs is a “Lisp-2”: functions and values have separate namespaces. A function definition
(defun foo …) and a function call
(foo …) use the function slot of the symbol
foo. A variable assignment
(setq foo …), a variable binding
(let ((foo …)) …), and a variable reference
x use the value slot of the symbol
To call a function which is stored in the value slot of a symbol, use
(funcall fn x)
More generally, but infrequently, the argument to
funcall can be any Lisp expression.
funcall is an ordinary function.
Lisp functions take a list of arguments. Sometimes, in addition to calling a variable function, you need to call the function with a variable list of arguments. In this case, use
apply instead of
funcall. The last argument to
apply is used as a list of remaining arguments.
In this particular case, where the code of the function is fully known, you can also use
cl-flet from the CL library that is distributed with Emacs. This doesn't let you easily pass the function around, which may or may not be an issue in your real program.
(require 'cl-lib) (let ((lexical-binding t) (x 4)) (cl-flet ((fn (y) (+ y 4))) (pcase x (10 (- x 2)) (4 (fn x)))))