1

For example:

(setf s 2)
    s => 2

(setf list1 '(1 s 3 4))
    list1 => (1 s 3 4)

How do i get it to add the value stored in s to the list? For this example I would want to use s to generate a list (1 2 3 4) I have a lisp book I'm reading and I can't seem to find any mention of how to do this so I thought i'd ask. Thanks

4
  • 1
    '(1 ,s 3 4) should work (note the comma in front of s). Commented Feb 17, 2017 at 9:16
  • I just tried that and I get the following error (comma is illegal outside of backquote) Commented Feb 17, 2017 at 9:19
  • 1
    Yes, you should use a backquote (`), not a quote ('). Commented Feb 17, 2017 at 9:21
  • Thanks! Silly of me Commented Feb 17, 2017 at 9:24

2 Answers 2

1

So quoted data in Scheme are like String constants.. If I wrote "1 s 3 4" in Java I wouldn't be able to get s replaced with the variable contents. I 'd have to write "1 " + s + " 3 4". In Lisp we have backquote to do this in list structures:

`(1 ,s 3 4)
; ==> (1 2 3 4)

Note that this is a trick.. It's like "1 $s 3 4" in PHP as it's representing code that creates the list with the unquoted variables evaluated and return a new list structure. Under the hood it's very similar to writing:

(list 1 s 3 4)
; ==> (1 2 3 4)

And of course list is not a primitive since it just uses cons. What it does is this:

(cons 1 (cons s (cons 3 (cons 4 '()))))
; ==> (1 2 3 4)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation. Works great now!
1

I would want to use s to generate a list (1 2 3 4)

The function list can be handy:

CL-USER 14 > (let ((s '2))
               (list 1 s 3 4))
(1 2 3 4)

The function LIST creates a fresh new list from its arguments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.