使用 Lisp 检查循环中的偶数和奇数

Checking for even and odd values in a loop with Lisp

我不明白为什么以下 lisp 程序显示 15 行输出而不是 10 行:

(defparameter x 1)
(dotimes (x 10)
  (if (oddp x)
    (format t "x is odd~%"))
    (format t "x is even~%"))

我在 Windows 10 机器上使用 CLISP 2.49。

当前:

(if (oddp x)
    (format t "x is odd~%"))    ; <- extra parenthesis
    (format t "x is even~%"))

求职:

(if (oddp x)
    (format t "x is odd~%")
    (format t "x is even~%"))

您在 else 语句之前转义 if 形式,因此 else 语句总是被打印,而 if 语句被打印 5 次。

除了已接受的答案外,请注意,使用 auto-indenting 编辑器(例如使用 Emacs)可以轻松发现这些类型的错误。您的代码auto-indents如下:

(dotimes (x 10)
  (if (oddp x)
      (format t "x is odd~%"))
  (format t "x is even~%"))

if 和第二个 format 表达式垂直对齐(它们是树中以 dotimes 为根的兄弟姐妹),而您希望第二个 format 仅发生当测试失败时,与第一个相同的深度。

备注

您还可以分解一些代码:

(format t 
        (if (oddp x) 
          "x is odd~%" 
          "x is even~%"))

甚至:

(format t
        "x is ~:[even~;odd~]~%" 
        (oddp x))

以上依赖conditional formatting.