需要帮助理解错误 (F3 '(6 3 4 1)) is not a real number Lisp 代码

Need help understanding an error (F3 '(6 3 4 1)) is not a real number Lisp code

这是我的 lisp 代码。我正在尝试解决这个问题:

Define function f3 that takes a simple list of integers as an argument and returns the number (count) of integers in the list which are between -3 and +15 (-3 and +15 included). For example:

LISP> (f3 '(1 -2 17 -4))
2

这是我对这个问题的看法,我被卡住了。我不知道我做错了什么。

(defun f3 (x)
  (if (null x)
      0
    (if (>(car x) - 3) 
        (if (<(car x) 15)
            (+ 1(f3 (cdr x)))
          (f3 (cdr x))
          (f3 (cdr x))))))

第二个 (f3 (cdr xx)) 后的括号不够。如您所见,当代码正确缩进时,将最后 2 个递归调用放在同一个 if 中;最后一个应该在之前的 if.

但是 -315 不需要单独的 if 表达式。您可以将测试与 and 结合使用,或者利用它对两个端点进行相同比较这一事实并使用 (<= -3 (car x) 15)。另请注意,问题表明端点已包含在内,因此您应该使用 <= 而不是 <.

最后,-3之间不应该有space。我怀疑那只是一个复制错误,因为在那种情况下你会得到一个不同的错误。

(defun f3 (x)
  (if (null x)
      0
    (if (<=  -3 (car x) 15)
        (+ 1 (f3 (cdr x)))
      (f3 (cdr x)))))

Common Lisp 是一门非常成熟的语言,因此它的“standard-library”中有很多实用的东西。在您的情况下,您只需使用函数 count-if 并编写正确的谓词。

(defun count-in-range (values)
       (count-if (lambda (x) (and (>= x -3) (<= x 15))) values))

;; (count-in-range '(1 -2 17 -4))
;; => 2