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

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

dynamic and lexical scope, attempted summary with example (was: Re: run-


From: Emanuel Berg
Subject: dynamic and lexical scope, attempted summary with example (was: Re: run-with-timer does not display message)
Date: Sun, 20 Jul 2014 23:28:58 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (gnu/linux)

As always, I think it is easier to discuss in terms of
an example...

This function is what started it all:

(defun shortcut-to-file (key-prefix key file-prefix file)
  "Make shortcut with key KEY-PREFIX KEY to FILE-PREFIX FILE."
  (global-set-key
   (format "%s%s" key-prefix key)
   `(lambda ()
      (interactive)
      (do-show-file (format "%s%s" ,file-prefix ,file)) )))

Is this correct?

In dynamic scope:
      
1. At the 4th line, the line that starts with `format',
   we see use of the arguments to the parameters
   `key-prefix' and `key' - because they are inside the
   defun, it is clear that those refer the the
   arguments passed as parameters.

2. At the 7th, last line, `file-prefix' and `file'
   appears. Those are preceded by commas so, in
   combination with the backtick, their values will be
   inserted - hard-coded. This bypasses the whole
   problem because it eliminates all evaluation of
   symbols (it is like Caesar and the Gordian
   knot). The drawback is that the lambda can't be
   byte-compiled as it is formally "just" a list.

3. If the lambda wasn't backticked and shot with
   commas, the defun would evaluate fine and even
   calling it wouldn't raise an error. However, when
   the keystroke was actually hit, the lambda wouldn't
   be within the defun anymore - it would be in the
   wild, and `file-prefix' and `file' would be
   interpreted as symbols, i.e., global
   variables. Those are probably not defined... but if
   they were, with `setq' for example, those values
   would be used (this would make for a total mess).

In lexical scope, the backtick and the commas aren't
necessary. The lambda can be expressed as a lambda and
nothing else, which means it can be byte-compiled. When
the symbols are encountered, those aren't looked for as
global variables, but rather the history of the place
they occurred in code is drilled down, until a scope is
encountered where they are defined, and those values
are used.

-- 
underground experts united


reply via email to

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