首页 > 解决方案 > 使用 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。

标签: lispcommon-lispclisp

解决方案


除了公认的答案,请注意使用自动缩进编辑器(例如使用 Emacs)可以轻松发现这些错误。您的代码自动缩进如下:

(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))

以上依赖于条件格式


推荐阅读