1

How do I create a quoted list in Lisp that uses the symbols' values in the list, rather than the symbols themselves? For example, take two variables foo and bar, foo = "hello" and bar = "world". How do I get a list that contains "hello" "world" from these two variables. The best thing I can think of is this:

;; This is Emacs Lisp
(let ((foo "hello")
      (bar "world"))
  (message (prin1-to-string '(foo bar)))
;; prints "(foo bar)"

But this is wrong. What's the right way to do this?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
Ron
  • 1,989
  • 2
  • 17
  • 33
  • in Common Lisp, also: ``(let (...) (msg `(foo ,foo bar ,bar)))``. Automatically translated into ``(let (...) (msg (list 'foo foo 'bar bar)))``. – Will Ness Dec 22 '13 at 12:04
  • Possible duplicate of [When to use 'quote in Lisp](http://stackoverflow.com/questions/134887/when-to-use-quote-in-lisp) – sds Dec 05 '16 at 20:05

2 Answers2

3

Never mind, further experimentation revealed that the answer is (list foo bar).

(let ((foo "hello")
      (bar "world"))
  (message (prin1-to-string (list foo bar)))
;; prints '("hello" "world")'

EDIT: Another way of achieving this is using `(,foo ,bar)

(let ((foo "hello")
      (bar "world"))
  (message (prin1-to-string `(,foo ,bar)))
;; prints '("hello" "world")'
Ron
  • 1,989
  • 2
  • 17
  • 33
2

This is a rather strange question since if you want the value of foo and bar you are not suppose to quote it. Using only primitives you make such list:

(let ((foo "hello")
      (bar "world"))
  (cons foo (cons bar nil))) ; ==> ("hello" "world")

There is a function called list that does the cons for you, thus (list foo bar 'foo 'bar) does the same as (cons foo (cons bar (cons 'foo (cons 'bar nil)))) ==> ("hello" "world" foo bar) in the same scope as the code above.

With quasiquoting (backquoting) you can mix constants so that `(,foo ,bar foo bar) is the equivalent, but be aware that constant tails, like '(foo bar) in my example, get reused.

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
Sylwester
  • 47,942
  • 4
  • 47
  • 79