emacs: get lexically bound variable value by name [duplicate] - emacs

This question already has answers here:
Lexical eval in emacs24
(3 answers)
Closed 9 years ago.
The following does not work with void variable error. What should eval be replaced with to get this to work?
;; -*- lexical-binding: t -*-
(defun foo2 ()
(let ((b 'lkj))
(lambda ()
(eval 'b t))))
(funcall (foo2))
symbol-value doesn't work either (as documented).

Looking up a variable's value by name is fundamentally incompatible with proper lexical scoping, because proper lexical scoping admits alpha-renaming, i.e. (consistently) renaming a variable should not affect the result.
Of course, if you really must know, you can hack things around in some cases, doing things like:
(funcall `(closure ,(nth 1 <someclosure>) () <exp>))
which might evaluate <exp> in the same scope as the one from where <someclosure> comes. It won't work if <someclosure> was byte-compiled (or if I made a mistake).

Related

Emacs: What does the "#" before function symbol imply? [duplicate]

This question already has answers here:
When should Emacs #'function syntax be used?
(3 answers)
Closed 6 years ago.
For example: (add-hook 'after-init-hook #'global-flycheck-mode)
Why # needs to be prepended to 'global-flycheck-mode?
#' is just a short-hand for using function. From the elisp manual:
-- Special Form: function function-object
This special form returns FUNCTION-OBJECT without evaluating it.
In this, it is similar to ‘quote’ (see Quoting). But unlike
‘quote’, it also serves as a note to the Emacs evaluator and
byte-compiler that FUNCTION-OBJECT is intended to be used as a
function. Assuming FUNCTION-OBJECT is a valid lambda expression,
this has two effects:
• When the code is byte-compiled, FUNCTION-OBJECT is compiled
into a byte-code function object (see Byte Compilation).
• When lexical binding is enabled, FUNCTION-OBJECT is converted
into a closure. See Closures.
You can see the difference when byte-compiling/loading this
(setq f1 '(lambda (x) (* x x)))
(setq f2 #'(lambda (x) (* x x)))
Only the the correctly quoted form is byte-compiled:
(byte-code-function-p f1)
nil
(byte-code-function-p f2)
t

sbcl Common Lisp incf warning [duplicate]

This question already has answers here:
setq and defvar in Lisp
(4 answers)
Closed 6 years ago.
I was following a tutorial on lisp and they did the following code
(set 'x 11)
(incf x 10)
and interpreter gave the following error:
; in: INCF X
; (SETQ X #:NEW671)
;
; caught WARNING:
; undefined variable: X
;
; compilation unit finished
; Undefined variable:
; X
; caught 1 WARNING condition
21
what is the proper way to increment x ?
This is indeed how you are meant to increment x, or at least one way of doing so. However it is not how you are meant to bind x. In CL you need to establish a binding for a name before you use it, and you don't do that by just assigning to it. So, for instance, this code (in a fresh CL image) is not legal CL:
(defun bad ()
(setf y 2))
Typically this will cause a compile-time warning and a run-time error, although it may do something else: its behaviour is not defined.
What you have done, in particular, is actually worse than this: you have rammed a value into the symbol-value of x (with set, which does this), and then assumed that something like (incf x) will work, which it is extremely unlikely to do. For instance consider something like this:
(defun worse ()
(let ((x 2))
(set 'x 4)
(incf x)
(values x (symbol-value 'x))))
This is (unlike bad) legal code, but it probably does not do what you want it to do.
Many CL implementations do allow assignment to previously unbound variables at the top-level, because in a conversational environment it is convenient. But the exact meaning of such assignments is outwith the language standard.
CMUCL and its derivatives, including SBCL, have historically been rather more serious about this than other implementations were at the time. I think the reason for this is that the interpreter was a bunch more serious than most others and/or they secretly compiled everything anyway and the compiler picked things up.
A further problem is that CL has slightly awkward semantics for top-level variables: if you go to the effort to establish a toplevel binding in the normal way, with defvar & friends, then you also cause the variable to be special -- dynamically scoped -- and this is a pervasive effect: it makes all bindings of that name special. That is often a quite undesirable consequence. CL, as a language, has no notion of a top-level lexical variable.
What many implementations did, therefore, was to have some kind of informal notion of a top-level binding of something which did not imply a special declaration: if you just said (setf x 3) at the toplevel then this would not contage the entire environment. But then there were all sorts of awkward questions: after doing that, what is the result of (symbol-value 'x) for instance?
Fortunately CL is a powerful language, and it is quite possible to define top-level lexical variables within the language. Here is a very hacky implementation called deflexical. Note that there are better implementations out there (including at least one by me, which I can't find right now): this is not meant to be a bullet-proof solution.
(defmacro deflexical (var &optional value)
;; Define a cheap-and-nasty global lexical variable. In this
;; implementation, global lexicals are not boundp and the global
;; lexical value is not stored in the symbol-value of the symbol.
;;
;; This implementation is *not* properly thought-through and is
;; without question problematic
`(progn
(define-symbol-macro ,var (get ',var 'lexical-value))
(let ((flag (cons nil nil)))
;; assign a value only if there is not one already, like DEFVAR
(when (eq (get ',var 'lexical-value flag) flag)
(setf (get ',var 'lexical-value) ,value))
;; Return the symbol
',var)))

What does the `#` mean in elisp? [duplicate]

This question already has answers here:
What is the role of the # character in Emacs Lisp?
(2 answers)
Closed 7 years ago.
Quite likely this is a dumb question, but I haven't come across the # symbol in the bits of elisp I have read, and was wondering what it means (preceded by a , as well) in this code? I have had some difficulty providing the proper search phrase I think.
In case of link rot:
(defmacro zenburn-with-color-variables (&rest body)
"`let' bind all colors defined in `zenburn-colors-alist' around BODY.
Also bind `class' to ((class color) (min-colors 89))."
(declare (indent 0))
`(let ((class '((class color) (min-colors 89)))
,#(mapcar (lambda (cons)
(list (intern (car cons)) (cdr cons)))
zenburn-colors-alist))
,#body))
This is an elisp macro definition, it defines a template for code to be substituted by other code at compile time. A decent intro is chapter 7 of Paul Graham's On Lisp
http://www.paulgraham.com/onlisptext.html
Ask Emacs, by checking the index of the elisp manual:
C-hig (elisp) RET
I # RET
Follow result: * ,# (with backquote) [Index]: Backquote. (line 29)
You can also "splice" an evaluated value into the resulting list,
using the special marker ‘,#’. The elements of the spliced list become
elements at the same level as the other elements of the resulting list.
The equivalent code without using ‘`’ is often unreadable. Here are
some examples:
[...]

why is the warning sign popping out? in lisp programming [duplicate]

I'm a total Lisp n00b, so please be gentle.
I'm having trouble wrapping my head around CL's idea of an [un-]declared free variable. I would think that:
(defun test ()
(setq foo 17)
)
would define a function that declares a variable foo and set it to 17. However, instead I get
;Compiler warnings :
; In TEST: Undeclared free variable FOO
My actual example case is a bit bigger; my code (snippet) looks like this:
(defun p8 ()
;;; [some other stuff, snip]
(loop for x from 0 to (- (length str) str-len) do
(setq last (+ x str-len)) ; get the last char of substring
(setq subs (subseq str x last)) ; get the substring
(setq prod (prod-string subs)) ; get the product of that substring
(if (> prod max) ; if it's bigger than current max, save it
(setq max prod)
(setq max-str subs)
)
)
;;; [More stuff, snip]
)
and that gives me:
;Compiler warnings for "/path/to/Lisp/projectEuler/p6-10.lisp":
; In P8: Undeclared free variable LAST (2 references)
;Compiler warnings for "/Volumes/TwoBig/AllYourBits-Olie/WasOnDownBelowTheOcean/zIncoming/Lisp/projectEuler/p6-10.lisp" :
; In P8: Undeclared free variable PROD (3 references)
;Compiler warnings for "/Volumes/TwoBig/AllYourBits-Olie/WasOnDownBelowTheOcean/zIncoming/Lisp/projectEuler/p6-10.lisp" :
; In P8: Undeclared free variable SUBS (3 references)
;Compiler warnings for "/Volumes/TwoBig/AllYourBits-Olie/WasOnDownBelowTheOcean/zIncoming/Lisp/projectEuler/p6-10.lisp" :
; In P8: Undeclared free variable =
Yes, yes, I realize that I'm using far too many intermediate variables, but I'm trying to understand what's going on before I get too fancy with compressing everything down to the minimal typed characters, as seems popular in the CL world.
So, anyway... can someone explain the following:
Under what conditions does Lisp "declare" a variable?
Is the scope of said variable other than the enclosing (...) around the setq statement?! (That is, I would expect the var to be valid & scoped for everything from (... (setq ...) ...) the parens 1 level outside the setq, no?
Am I mis-interpreting the Undeclared free variable message?
Any other hints you care to give that would help me better grok what's going on, here.
NOTE: I'm fairly expert with C, Java, Javascript, Obj-C, and related procedural languages. I get that functional programming is different. For now, I'm just wrestling with the syntax.
Thanks!
P.S. If it matters, defun p8 is in a text file (TextMate) and I'm running it on Clozure CL. Hopefully, none of that matters, though!
In lisp variables may be declared usingdefparameterordefvar.
(defparameter var1 5)
(defvar var2 42)
This results in global (dynamic) variables.
The difference between defvarand defparameteris that defvardoes not reinitialize an already existing variable.
Local (lexical) variables are introduced e.g using let or let* (which initializes the variables sequentially).
Undeclared free variable means that you have used (here setq-ed) a variable that it is not bound in the context it is used. It may then be declared for you, but then probably as a global (dynamic) variable. The consequence of this is that if you use undeclared variables with the same name in several functions, you will be referencing the same variable in all of the functions.
Your code can be written like this:
(loop for x from 0 to (- (length str) str-len) do
(let* ((last (+ x str-len)) ; get the last char of substring
(subs (subseq str x last)) ; get the substring
(prod (prod-string subs))) ; get the product of that substring
(if (> prod max) ; if it's bigger than current max, save it
(setq max prod)
(setq max-str subs))))
Using the variable-binding properties of loop, it may also be written as
(loop for x from 0 to (- (length str) str-len)
for last = (+ x str-len)
for subs = (subseq str x last)
for prod = (prod-string subs)
when (> prod max) do
(setq max prod)
(setq max-str subs))
In Lisp variable declaration may be performed in many ways. The most notable are:
declaring global (they are properly called special) variables with defparameter and defvar
declaring local variables with let, let*, multiple-value-bind, destructuring-bind, and other binding forms
as function arguments
You can read about their scope in many places as well, for instance in CLtL2.
setq/setf are not variable declaration operators, but variable modification operators, as implied by their names.
PS. In interactive mode some implementation would use the DWIM approach and declare the variable as special behind the scenes, if you try to set an undeclared variable, but this is purely for convenience.
The Common Lisp HyperSpec (basically its the Common Lisp standard in HTML form) says:
http://www.lispworks.com/documentation/HyperSpec/Body/s_setq.htm
Assigns values to variables.
So SETQ only assigns values to variables. It does not declare them.
Variable definitions are done globally with DEFVAR, DEFPARAMETER, ...
(defparameter *this-is-a-global-dynamic-variable* 'yep)
Variable definitions are done locally with DEFUN, LET, LET*, LOOP, and many others.
(defun foo (v1 v2)
...)
(let ((v1 10)
(v2 20))
...)
(loop for v1 in '(10 30 10 20)
do ...)
This is basic Lisp and it would be useful to read an introduction. I would recommend:
http://www.cs.cmu.edu/~dst/LispBook/
Above book is free for download.
Additionally the above mentioned Common Lisp Hyperspec provides you with the definitions for Common Lisp and describes the various facilities (DEFUN, LOOP, DEFPARAMETER, ...) in detail.

When to use defparameter instead of setf?

I'm currently reading the book Land of LISP, and I'm just working through the first chapter. In there, there is a little program written where the computer guesses numbers between 1 and 100. Its code is as follows:
(defparameter *small* 1)
(defparameter *big* 100)
(defun guess-my-number ()
(ash (+ *small* *big*) -1))
(defun smaller ()
(setf *big* (1- (guess-my-number)))
(guess-my-number))
(defun bigger ()
(setf *small* (1+ (guess-my-number)))
(guess-my-number))
(defun start-over ()
(defparameter *small* 1)
(defparameter *big* 100)
(guess-my-number))
So far, I understand what happens, and Using 'ash' in LISP to perform a binary search? helped me a lot in this. Nevertheless there's one thing left that puzzles me: As far as I have learned, you use setf to assign values to variables, and defparameter to initially define variables. I also have understood the difference between defparameter and defvar(at least I believe I do ;-)).
So now my question is: If I should use setf to assign a value to a variable once it had been initialized, why does the start-over function use defparameter and not setf? Is there a special reason for this, or is this just sloppiness?
The function is just:
(defun start-over ()
(setf *small* 1)
(setf *big* 100)
(guess-my-number))
It is already declared to be a special global variable. No need to do it inside the function again and again.
You CAN use DEFPARAMETER inside a function, but it is bad style.
DEFPARAMETER is for declaring global special variables and optional documentation for them. Once. If you need to do it several times, it's mostly done when a whole file or system gets reloaded. The file compiler also recognizes it in top-level position as a special declaration for a dynamically bound variable.
Example:
File 1:
(defparameter *foo* 10)
(defun foo ()
(let ((*foo* ...))
...))
File 2:
(defun foo-start ()
(defparameter *foo* 10))
(defun foo ()
(let ((*foo* ...))
...))
If Lisp compiles File 1 fresh with compile-file, the compiler recognizes the defparameter and in the following let we have a dynamic binding.
If Lisp compiles File 2 fresh with compile-file, the compiler doesn't recognize the defparameter and in the following let we have a lexical binding. If we compile it again, from this state, we have a dynamic binding.
So here version 1 is better, because it is easier to control and understand.
In your example DEFPARAMETER appears multiple times, which is not useful. I might ask, where is the variable defined and the answer would point to multiple source locations...
So: make sure that your program elements get mostly defined ONCE - unless you have a good reason not to do so.
So you have global variables. Those can be defined by defconstant (for really non-chainging stuff), defparameter (a constant that you can change) and defvar (a variable that does not overwrite if you load.
You use setf to alter the state of lexical as well and global variables. start-over could have used setf since the code doesn't really define it but change it. If you would have replaced defparameter with defvar start-over would stop working.
(defparameter *par* 5)
(setf *par* 6)
(defparameter *par* 5)
*par* ; ==> 5
(defvar *var* 5)
(setf *var* 6)
(defvar *var* 5)
*var* ; ==> 6
defconstant is like defparameter except once defined the CL implementation is free to inline it in code. Thus if you redefine a constant you need to redefine all functions that uses it or else it might use the old value.
(defconstant +c+ 5)
(defun test (x)
(+ x +c+))
(test 1) ; ==> 6
(defconstant +c+ 6)
(test 1) ; ==> 6 or 7
(defun test (x)
(+ x +c+))
(test 1) ; ==> 7
Normally, one would use defvar to initialy define global variables. The difference between defvar and defparameter is subtle, cf. the section in the CLHS and this plays a role here: defparameter (in contrast to defvar) assigns the value anew, whereas defvar would leave the old binding in place.
To address what to use: In general, defvar and friends are used as top-level forms, not inside some function (closures being the most notable exception in the context of defun). I would use setf, not defparameter.
For a beginner symbols, variables, etc. can be a bit surprising. Symbols are surprisingly featureful. Just to mention a few things you can ask a symbol for it's symbol-value, symbol-package, symbol-name, symbol-function etc. In addition symbols can have a varying amount of information declared about them, for example a type, that provides advice the compile might leverage to create better code. This is true of all symbols, for example *, the symbol you use for multiplication has a symbol-function that does that multiplication. It also has a symbol-value, i.e. the last value returned in the current REPL.
One critical bit of declarative information about symbols is if they are "special." (Yeah, it's a dumb name.) For good reasons it's good practice to declare all global symbols to be special. defvar, defparameter, and defconstant do that for you. We have a convention that all special variables are spelled with * on the front and back, *standard-output* for example. This convention is so common that some compilers will warn you if you neglect to follow it.
One benefit of declaring a symbol as special is that it will suppress the warning you get when you misspell a variable in your functions. For example (defun faster (how-much) (incf *speed* hw-much)) will generate a warning about hw-much.
The coolest feature of a symbol that is special is that it is managed with what we call dynamic scoping, in contrast to lexical scope. Recall how * has the value of the last result in the REPL. Well in some implementations you can have multiple REPLs (each running in it's own thread) each will want to have it's own *, it's own *standard-output*, etc. etc. This is easy in Common Lisp; the threads establish a "dynamic extent" and bind the specials that should be local to that REPL.
So yes, you could just setf *small* in you example; but if you never declare it to be special then you are going to get warnings about how the compiler thinks you misspelled it.