CLISP报错‘variable has no value’,求列表配对元素提取的搜索关键词
Hey there! Let's break down what's going on with your Lisp function and fix that "variable myr has no value" error step by step.
Why You're Getting the Error
The main issue here is incorrect use of Lisp's prefix notation. Unlike languages like Java or Python, Lisp requires all function calls (including recursive ones) to follow the format (function-name arg1 arg2 ...). When you wrote myr(b CDR(a)), Lisp interprets this as trying to evaluate the variable myr (not call the function) and pass (b CDR(a)) as an argument to it—since myr is a function, not a bound variable, you get that error.
You also have a few other syntax and logic issues in your code:
- Function calls like
CAAR(a)are wrong; it should be(caar a)(prefix notation for thecaarfunction). =is only for comparing numbers—useeqorequalto compare symbols/atoms.- The
ifsyntax is invalid: Lisp'sifonly takes three parts ((if condition then else)), but you have four elements in yourifform. - Your parameter order and recursive logic don't align with your goal of extracting matching elements.
Corrected Function
Here's a working version of your function that does what you want—extracting all second elements from pairs where the first element matches your target:
(defun myr (target lst) (cond ((null lst) nil) ; Stop recursion when the list is empty ((eq (caar lst) target) ; If current pair matches, keep the second element and recurse on the rest (cons (cdar lst) (myr target (cdr lst)))) (t ; If no match, skip the current pair and recurse (myr target (cdr lst)))))
How to Use It
Call it with your target symbol and the list of pairs:
(myr 'c '((c a) (c b) (d f) (d g)))
This will return (a b)—Lisp uses lists for collections by default, which matches your expected result of 'a' 'b'.
Keywords to Search for Learning
Since you're new to Lisp, these topics will help you build a solid foundation:
- Lisp prefix notation: The core syntax rule that governs all function calls and expressions.
- Common Lisp defun: How to properly define functions with parameters and body forms.
- Common Lisp recursion basics: Understanding how to structure recursive functions with clear termination conditions.
- Common Lisp list operations (car, cdr, caar, cdar): These are essential for manipulating lists and nested pairs.
- Common Lisp equality checks (eq, equal, eql): Knowing which comparison function to use for different data types.
内容的提问来源于stack exchange,提问作者YJS

