公共LISP调试(包括代码)



我希望对我的代码进行快速修复,该代码列出了数字,数字列表和阈值列表,并返回数字列表中的项目数量大于阈值。我只是不知道怎么了,我对调试不熟悉。我是Stackoverflow的新手,一般来说,LISP ...任何评论/批评/建议都将受到欢迎。谢谢!

ex)(count-grater-and(列表1 2 3 4 5 6 6 7)5)=> 3

(defun count-greater-than (numberlist threshold)
  (if (null numberlist) 0
    (counter (numberlist threshold 0)))
  (defun counter (numberlist threshold count)
    (cond ((null numberlist) count)
          ((> (first numberlist) threshold) (counter (rest numberlist) threshold (+ 1 count)))
          (t (counter (rest numberlist) threshold count)))))

首先,请注意,标准实际上包含可以帮助这样的事情的功能。有一个有用的 count-if-if 函数,可以采用谓词并计算列表中的多少元素满足它。对于您的情况,您可以这样做:

CL-USER> (count-if #'(lambda (x)
                       (> x 5))
                   (list 1 2 3 4 5 6 6 7))
;=> 3

CL-USER> (defun count-greater-than (numbers threshold)
           (count-if (lambda (n) (> n threshold)) numbers))
COUNT-GREATER-THAN
CL-USER> (count-greater-than (list 1 2 3 4 5 6 6 7) 5)
3
CL-USER> (count-greater-than (list 1 2 3 4 5 6 6 7) 6)
1

在您的特殊情况下,看起来您正在手动执行此操作,但是您的括号错误。看起来您正在尝试创建一个名为 Counter 的本地辅助函数。您可以用 defun 在功能之外定义它,例如:

(defun count-greater-than (numberlist threshold)
  (if (null numberlist) 0
    (counter (numberlist threshold 0))))
(defun counter (numberlist threshold count)
  (cond ((null numberlist) count)
        ((> (first numberlist) threshold) (counter (rest numberlist) threshold (+ 1 count)))
        (t (counter (rest numberlist) threshold count))))

,或者您可以使用标签使用本地定义来完成此操作:

(defun count-greater-than (numberlist threshold)
  (labels ((counter (numberlist threshold count)
             (cond ((null numberlist) count)
                   ((> (first numberlist) threshold) (counter (rest numberlist) threshold (+ 1 count)))
                   (t (counter (rest numberlist) threshold count)))))
    (if (null numberlist) 0
        (counter numberlist threshold 0))))

注释

正如Xach在注释中指出的那样,您实际上可以使用 count 's 更简洁地执行此操作:test 参数。我不知道它是否明确地捕获了"用此属性来计算事物"的概念,但是它是一个非常简短的解决方案:

CL-USER> (count 5 (list 1 2 3 4 5 6 6 7) :test #'<)
;=> 3

这计算了列表中有多少次,但是诀窍是,而不是使用 eql = 检查列表元素是否为5,而是使用&lt; 。也就是说, count 最终会检查(&lt; 5 1),然后(&lt; 5 2)hellip; ,,strong>(&lt; 5 6)(&lt; 5 7)指定的测试将以该顺序调用参数。上的词汇表条目满足测试 say(添加了强调):

  1. (对于两个参数测试)处于一个状态,以至于序列函数的测试参数返回true的两位谓词 当给出时,第一个参数是被考虑的对象,并且 当给出时,第二个参数是调用 序列函数在序列元素上的关键参数 函数的序列参数正在测试以均等;

最新更新