[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Closures in Emacs and their usage scenarios.

From: Marcin Borkowski
Subject: Re: Closures in Emacs and their usage scenarios.
Date: Sun, 10 Oct 2021 20:25:15 +0200
User-agent: mu4e 1.1.0; emacs 28.0.50

On 2021-10-10, at 16:16, Emanuel Berg via Users list for the GNU Emacs text 
editor <> wrote:

> Hongyi Zhao wrote:
>> I'm learning "Advising Emacs Lisp Functions" now.
>> According to my current superficial understanding, it seems
>> that both closure and advice function are intended to
>> provide a clean and concise method to patch/repair/adapt the
>> existing function/macros with a most consistent way.
> That should be one of many use cases for advising functions,
> I don't know how one does that with closure tho ...
> I've still only seen two use cases for closures, one is the
> persistent variable (in C you'd use a static variable, in
> Python just a global one) and the other one is the sharing of
> one "almost global" variable between two or more functions (in
> both C and Python, that would be a real global variable
> instead).
> And the second use case is a version of the first, or
> extension perhaps, since that variable (or set of variables)
> would also be persistent. It looks a lot like OOP to me -
> I say it in that order because I learned the OOP basics/theory
> before I heard of closures, but I expect closures were
> actually first, right? - and it is even the very core of OOP
> (the coupling/enclosure of data and functions/methods that
> operate that data) - so we can say not without reason that
> Lisp is the original OOP - with the core stuff implemented in
> such as simple way - but without all the other stuff that no
> one uses anyway :)

Yet another use (which of course - technically - is again a variant of
the same thing) is generating a closure whose behavior depends on the
argument of the function that defines it.

<shameless plug>

A simple example from my book:

(defun negate (fun)
  "Return a function returning the logical opposite of FUN."
  (lambda (&rest args)
    (not (apply fun args))))

</shameless plug>

so that (negate #'zerop) behaves like a function testing its argument
for "non-zeroness" (i.e., returning t unless its argument is 0, when it
returns nil).

As a homework, try to use it under dynamic binding and see why it won't
work.  (See also this thread: .)


Marcin Borkowski

reply via email to

[Prev in Thread] Current Thread [Next in Thread]