help-gnu-emacs
[Top][All Lists]
Advanced

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

Re: Real-life examples of lexical binding in Emacs Lisp


From: Andreas Röhler
Subject: Re: Real-life examples of lexical binding in Emacs Lisp
Date: Wed, 17 Jun 2015 18:19:28 +0200
User-agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Thunderbird/31.4.0


Am 17.06.2015 um 16:42 schrieb Stefan Monnier:
Without lexical binding, to try to get some independence from other
functions, you would have to PREFIX ALL THE LOCAL VARIABLES WITH
FUNCTION SPECIFIC PREFIXES!
Actually, not really.  The Elisp convention to only use prefixes for
global variables is 99% sufficient.  In your example, the problem is
that `some-function' modifies the (presumably global) variable
`scratch-buffer' and that this variable does not have an
appropriate prefix.

The only case where non-prefixed local variables cause problem is when
you introduce higher-order functions, as in:

    (defun my-map (f l)
      (if l (cons (funcall f (car l)) (my-map f (cdr l)))))

    (defun my-function (input)
      (let ((l ...))
        (my-map (lambda (x) (unless (memq x l) (error "invalid mapping")))
                input)))

Suddenly the `l' used inside the lambda will not refer to the `l' nearby
but to the `l' argument of `my-map'.  For this reason, some higher-order
functions used to use weird argument names to try and avoid such
name capture.  Nowadays they can use lexical scoping and hence choose
their variable names sanely and without fear.



Checked this with

;;; -*- lexical-binding: t; -*-

(defun my-map (f l)
  (if l (cons (funcall f (car l)) (my-map f (cdr l)))))

(defun my-function (input)
  (let ((l ()))
    (my-map (lambda (x) (unless (memq x l) (error "invalid mapping")))
        input)))

(my-function '(4 5))

Got identic results also without lexical-binding seen here. l is taken from inside lambda in both modes.






reply via email to

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