You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CLISP报错‘variable has no value’,求列表配对元素提取的搜索关键词

Fixing Your Lisp Function & Understanding the Error

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 the caar function).
  • = is only for comparing numbers—use eq or equal to compare symbols/atoms.
  • The if syntax is invalid: Lisp's if only takes three parts ((if condition then else)), but you have four elements in your if form.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:31:32