Higher-order functions in Elisp

I created a function that returns a function in Elisp:

(defun singleton-set (elem) (defun f (n) (= n elem)) f) 

I try to run this in IELM and it fails:

 ELISP> (singleton-set 5) *** Eval error *** Symbol value as variable is void: f ELISP> ((singleton-set 5) 5) *** Eval error *** Invalid function: (singleton-set 5) 

Because of what is the difference between Lisp -1 and Lisp -2? I changed the code to

 (defun singleton-set (elem) (defun f (n) (= n elem)) #'f) 

And a call in (funcall (singleton-set 5) 5) , but now an error

*** Eval error *** Symbol value as variable is void: elem

I understand from elisp: capturing a variable from an internal function , which is related to the dynamic binding of Emacs Lisp.

How to make functions returning functions possible in Emacs Lisp? What is the reason that this mechanism is different from other languages ​​like Python, Scala or Clojure?

Related questions:

  • elisp functions as parameters and as return value
  • Elisp Interactive Function Name
  • How to create a temporary function in Emacs Lisp
  • In elisp, how do I put a function in a variable?
+8
dynamic-binding emacs elisp higher-order-functions
source share
3 answers

From NEWS for Emacs 24:

Lisp changes in Emacs 24.1

  • Now the code can now use lexical scaling instead of dynamic spanning. The lexical-binding variable allows you to use the lexical scope for local variables. Usually it is set through a local file variable in the first line of the file, in which case it applies to all the code in that file.

So, in Emacs 24:

 (setq lexical-binding t) (defun singleton-set (elem) (lambda (n) (= n elem))) (mapcar (singleton-set 1) '(0 1 2 3)) ===> (nil t nil nil) 
+9
source share

How to make functions returning functions possible in Emacs Lisp?

Using fake closures and lexical-let .

What is the reason that this mechanism is different from other languages ​​like Python, Scala or Clojure?

Richard Stallman answered this question in an article he wrote some time ago.

+4
source share
 (defun singleton-set (elem) `(lambda (n) (= n ,elem)) 

See: elisp functions as parameters and as return value

+3
source share

All Articles