3

'(1 2 3) gives me a list of three elements,

but

(setq A "apple")

'(A) gives me (A).

My question is how can I get the list '("apple") by referring variable A?

Kaushal Modi
  • 25,203
  • 3
  • 74
  • 179
yi.tang.uni
  • 1,007
  • 8
  • 20

1 Answers1

11

How can I get the list '("apple") by referring variable A?

(list A)

or

`(,A)

How come there are several ways to construct a list?

  1. The ' in '(A) does not construct a list. The Lisp reader constructs a list when it reads (A). The ' prevents the Lisp REPL (i.e., the top-level loop) from evaluating the list that was read, so the list is just returned.

  2. Function list also does not construct a list, directly (depending on the Lisp implementation). The two list constructors in Lisp are cons and nil (aka ()). Function list uses those two constructors: (list) returns (), and (list X) returns (cons value-of-X nil), which is also written (value-of-X).


The backquote syntax of `(,A) is syntactic sugar for calls to functions such as list and cons. For example, in this case it could be an abbreviation for (list A). The comma (,) means evaluate what follows, and the backquote (`) means do not evaluate what follows, except for nested comma constructs. So `(,A) could be read as "evaluate A and wrap it in parens to make a singleton list". Backquote syntax shows you a picture of what it produces. You just need to plug in (substitute) the value of whatever follows a comma.

Drew
  • 75,699
  • 9
  • 109
  • 225