0

In example code in a book I'm reading, there's a line for a macro that provides shorthand for getting the global value of a symbol:

(defmacro sv (v) '(symbol-value `,v))

However, Allegro sees V as an unbound variable. I don't know how to change this macro to return the correct result, because I've never encountered a problem like this before. How would I get the global value of any symbol? Thanks for your help!

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
OrangeCalx01
  • 806
  • 2
  • 7
  • 21

1 Answers1

2

You need a backquote, not a single quote, in front of the whole s-exp:

(defmacro sv (v) `(symbol-value ,v))

(I know, it's hard to see: Just move the backquote in your original s-exp from in front of ,v and replace the single quote at the beginning of '(symbol-value ...)).

Backquote operates on expressions (lists), not individual atoms, per se. If what you typed was actually in the book, it's likely an erratum.

A slightly better version of sv:

(defmacro sv (v) `(symbol-value (quote ,v)))

or

(defmacro sv (v) `(symbol-value ',v))

In the last version, interchange the backquote and single quote in your original code. The penultimate version just makes it easier to read.

However, symbol-value only queries the current value bound to the variable. For example, this code evaluates to 'something-else:

(defparameter *wombat* 123)
(let ((*wombat* 'something-else)) (sv *wombat*))

The *wombat* in the let form is a lexical variable, whereas the *wombat* in the defparameter form is dynamic. The let form temporarily hides the visibility of the defparameter.

scooter me fecit
  • 1,053
  • 5
  • 15
  • But then, if I define a global variable X to be '123, (sv *x*) attempts to take the value of 123, which isn't a symbol. However, if I define x to be 'y, and define y to be 123, (sv x) would evaluate to 123. But it won't work for the rest of the program; the same error would keep popping up. Would it help if I posted the code sv is used in? – OrangeCalx01 Jan 11 '16 at 19:01
  • @OrangeCalx01: Updated answer for you. – scooter me fecit Jan 11 '16 at 19:13
  • Your last definition works - I believe it was a matter of text formatting that had me confused on quotes. ` and ' look like commas above letters, not as we see them. Thank you! – OrangeCalx01 Jan 11 '16 at 19:16
  • @OrangeCalx01: BTW: `symbol-value` just gets the current bound value for the symbol, not it's "global" (dynamic) value. – scooter me fecit Jan 11 '16 at 19:20
  • `Defparameter` declares the variable globally special, so the `*wombat*` in the `let` form is also special, its rebinding has dynamic extent. – Svante Jan 11 '16 at 22:25