barankin
barankin

Reputation: 1943

Expand variable in list in LISP

I wanted the following code to work. How do I make one-level variables expand?

(let* ((data1 10)
       (data2 '(data1 20)))
  (progn data2))

I expected (10 20) but in the fact I got (data1 20). Also I'd like to get (10 20 (data2)) from the following:

 (let* ((data1 10)
        (data2 30)
        (data3 '(data 10 20 '(data2)))
   (progn data3))

Upvotes: 1

Views: 583

Answers (2)

Rörd
Rörd

Reputation: 6681

As sepp2k said, the usual way to create lists at runtime is the list function. Quoted lists are list literals, of literal values.

But there's another way to create lists at runtime that looks more similar to quoted lists, the backquote. You could achieve what you want with

`(,data1 20)

Another thing regarding your examples: You don't need the progns there. progn is for sequencing multiple expressions and then return the value of the last of them, if it's just a single value expression, you can just use itself without the wrapping. But even if you had multiple expressions, you wouldn't need to use progn in this case, because let* implicitly puts a progn around the body.

Upvotes: 1

sepp2k
sepp2k

Reputation: 370092

The reason that the variable does not expand is that you quoted the whole list using '. ' is not how you create lists in lisp, it's how you quote them (i.e. cause them not to be evaluated).

To create a list containing the contents of data1 and the number 20, just use (list data1 20).

Upvotes: 2

Related Questions