Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variable names inside literals in Emacs Lisp?

Tags:

emacs

lisp

elisp

Is it possible to write e.g. a Vector literal which uses a variable inside so that the variable gets evaluated correctly and the resulting Vector doesn't just contain the name/symbol of the variable?

For example:

(setq inner ["d" "e"])
["a" "b" inner]

Results into:

["a" "b" inner]

But what I would want is:

["a" "b" ["d" "e"]]

I've done some Clojure coding before Elisp, there it works as I expected:

(def inner ["d" "e"])
user=> ["a" "b" inner]             
["a" "b" ["d" "e"]]

What's the fundamental thing I don't understand about Elisp here? I can of course work around this, but I'd like to understand what's going on.

like image 543
auramo Avatar asked Jan 21 '12 08:01

auramo


2 Answers

When using the vector syntax, the elements are considered constant. From the Emacs Lisp Reference Manual 6.4:

A vector, like a string or a number, is considered a constant for evaluation: the result of evaluating it is the same vector. This does not evaluate or even examine the elements of the vector.

On the other hand, you could use the vector function to create a vector where the elements are evaluated:

(setq inner ["d" "e"])
(vector "a" "b" inner)
=> ["a" "b" ["d" "e"]]
like image 89
Lindydancer Avatar answered Oct 29 '22 20:10

Lindydancer


use backquote literal. It's possible to use as same as for list.

(setq inner ["d" "e"])
`["a" "b" ,inner]
=> ["a" "b" ["d" "e"]]
like image 32
d5884 Avatar answered Oct 29 '22 21:10

d5884