It it possible to declare functions whose names are only available in the scope of another function, similar to
(defun my-fn (x y) (let ((my-local-fn (lambda (a b) (message "%S" (- a b))))) (my-local-fn x y) (my-local-fn y x))
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
You can use
cl-lib. The docstrings:
(cl-flet ((FUNC ARGLIST BODY...) ...) FORM...) Probably introduced at or before Emacs version 24.3. Make local function definitions. Each definition can take the form (FUNC EXP) where FUNC is the function name, and EXP is an expression that returns the function value to which it should be bound, or it can take the more common form (FUNC ARGLIST BODY...) which is a shorthand for (FUNC (lambda ARGLIST BODY)). FUNC is defined only within FORM, not BODY, so you can’t write recursive function definitions. Use ‘cl-labels’ for that. See info node ‘(cl) Function Bindings’ for details. (cl-labels ((FUNC ARGLIST BODY...) ...) FORM...) Probably introduced at or before Emacs version 24.3. Make local (recursive) function definitions. Each definition can take the form (FUNC ARGLIST BODY...) where FUNC is the function name, ARGLIST its arguments, and BODY the forms of the function body. FUNC is defined in any BODY, as well as FORM, so you can write recursive and mutually recursive function definitions. See info node ‘(cl) Function Bindings’ for details.
Note: see Stefan's anwser.
It seems that local functions are not a native feature of the language. The GNU Reference Manual does not cover "local functions" or mention it.
(defun foo (a b) (+ a b)) (let (foo) (setq val (symbol-value 'foo)) (symbol-function 'foo))
(symbol-function 'foo) returns
(lambda (a b) (+ a b)) whereas
(symbol-value 'foo) returns
Nevertheless, this feature is provided by the GNU Emacs Common Lisp Emulation (c.f. Function Bindings) which is a compatibility extension with Common Lisp for Elisp.
(cl-flet ((func (a b) (+ a b))) (func 1 1))