如何在Common Lisp中基于已有列表创建新列表?
Let's break down what's happening with your code and how to get the reversed list you're aiming for.
First, the issue with your current approach: when you use ' (quote) around the list ((caddr example1) (cadr example1) (car example1)), Common Lisp treats everything inside as literal symbols—it doesn't evaluate the caddr, cadr, or car calls. So instead of getting (3 2 1), you end up with a list of unevaluated function call symbols: ((CADDR EXAMPLE1) (CADR EXAMPLE1) (CAR EXAMPLE1)).
Here are three straightforward ways to fix this:
1. Use the list function
The list function evaluates each of its arguments and returns a new list with those evaluated values. This is the most direct way for your use case:
(setq example1 '(1 2 3)) (setq example2 (list (caddr example1) (cadr example1) (car example1))) ;; example2 will now be (3 2 1)
2. Use quasiquote (`) and unquote (,)
If you ever need to mix literal values with evaluated expressions in a list, quasiquote (backtick) plus unquote (comma) is perfect. It lets you quote most of the list but evaluate specific parts:
(setq example1 '(1 2 3)) (setq example2 `(,(caddr example1) ,(cadr example1) ,(car example1))) ;; example2 is (3 2 1) here too
3. Use reverse for a cleaner solution
Since you're just reversing the original list, why not use Common Lisp's built-in reverse function? It's more concise and works for any length of list:
(setq example1 '(1 2 3)) (setq example2 (reverse example1)) ;; example2 is (3 2 1)
Any of these approaches will give you the expected new list based on example1.
内容的提问来源于stack exchange,提问作者jakHunter

