Domanda

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?

È stato utile?

Soluzione

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")'

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top