Cai*_*inG 2 lisp clisp common-lisp
我不明白为什么以下lisp程序显示15行而不是10行:
(defparameter x 1)
(dotimes (x 10)
(if (oddp x)
(format t "x is odd~%"))
(format t "x is even~%"))
Run Code Online (Sandbox Code Playgroud)
我在Windows 10计算机上使用CLISP 2.49。
除了可接受的答案外,请注意,使用自动缩进编辑器(例如,使用Emacs)可以很容易地发现这些类型的错误。您的代码自动缩进如下:
(dotimes (x 10)
(if (oddp x)
(format t "x is odd~%"))
(format t "x is even~%"))
Run Code Online (Sandbox Code Playgroud)
在if与第二format表达式垂直对齐(他们是在根的树兄弟姐妹dotimes),而你想要的第二format只发生在测试失败时,在同一深度的第一个。
您还可以考虑一些代码:
(format t
(if (oddp x)
"x is odd~%"
"x is even~%"))
Run Code Online (Sandbox Code Playgroud)
甚至:
(format t
"x is ~:[even~;odd~]~%"
(oddp x))
Run Code Online (Sandbox Code Playgroud)
以上依赖于条件格式。
小智 6
当前:
(if (oddp x)
(format t "x is odd~%")) ; <- extra parenthesis
(format t "x is even~%"))
Run Code Online (Sandbox Code Playgroud)
通缉:
(if (oddp x)
(format t "x is odd~%")
(format t "x is even~%"))
Run Code Online (Sandbox Code Playgroud)
您要在else语句之前转义if形式,以便else语句始终被打印,而if语句则被打印5次。