Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do closures in Emacs Lisp?

I'm trying to create a function on the fly that would return one constant value.

In JavaScript and other modern imperative languages I would use closures:

function id(a) {     return function() {return a;}; } 

but Emacs lisp doesn't support those.

I can create mix of identity function and partial function application but it's not supported either.

So how do I do that?

like image 847
vava Avatar asked Feb 27 '09 03:02

vava


People also ask

What are closures in Lisp?

Common Lisp does not expose closures per se. Recall from Chapter 11 that a closure is a collection of closed-over variables retained by a function. (A closed-over variable is a variable found "free" in the function; this gets "captured" by the closure.

How do I Lisp in emacs?

In a fresh Emacs window, type ESC-x lisp-interaction-mode . That will turn your buffer into a LISP terminal; pressing Ctrl+j will feed the s-expression that your cursor (called "point" in Emacs manuals' jargon) stands right behind to LISP, and will print the result.

Is Emacs Lisp the same as Lisp?

By default, Common Lisp is lexically scoped, that is, every variable is lexically scoped except for special variables. By default, Emacs Lisp files are dynamically scoped, that is, every variable is dynamically scoped. The my-test. el is a lexically scoped file because of the first line.

What does #' mean in Emacs Lisp?

#'... is short-hand for (function ...) which is simply a variant of '... / (quote ...) that also hints to the byte-compiler that it can compile the quoted form as a function.


1 Answers

Found another solution with lexical-let

(defun foo (n)      (lexical-let ((n n)) #'(lambda() n)))  (funcall (foo 10)) ;; => 10 
like image 88
vava Avatar answered Sep 24 '22 08:09

vava