Lisp 带and运算符的If条件
如何使用IF条件和运算符? 我犯了个错误Lisp 带and运算符的If条件,lisp,common-lisp,clisp,Lisp,Common Lisp,Clisp,如何使用IF条件和运算符? 我犯了个错误 (princ"Enter a year: ") (defvar y(read)) (defun leap-year(y) (if(and(= 0(mod y 400)(= 0(mod y 4)) (print"Is a leap year")) (print"Is not")))) (leap-year y) 在lisp语言中,问题是缺少(或额外)括号
(princ"Enter a year: ")
(defvar y(read))
(defun leap-year(y)
(if(and(= 0(mod y 400)(= 0(mod y 4))
(print"Is a leap year"))
(print"Is not"))))
(leap-year y)
在lisp语言中,问题是缺少(或额外)括号 在您的情况下,函数定义中有多个括号问题,应该是:
(defun leap-year (y)
(if (and (= 0 (mod y 400)) (= 0(mod y 4)))
(print "Is a leap year")
(print "Is not")))
事实上,在这些语言的编程中,一个关于表达式对齐的良好规程和一个好的程序编辑器(比如Emacs)是非常重要的(我会说是“必不可少的”)
请注意,如果在REPL中使用该函数,则可以省略打印:
(defun leap-year (y)
(if (and (= 0 (mod y 400)) (= 0(mod y 4)))
"Is a leap year"
"Is not"))
最后,请注意,闰年的检查是。正确的定义可以是:
(defun leap-year (y)
(cond ((/= 0 (mod y 4)) "no")
((/= 0 (mod y 100)) "yes")
((/= 0 (mod y 400)) "no")
(t "yes")))
或者,如果,则使用:
(defun leap-year (y)
(if (or (and (zerop (mod y 4))
(not (zerop (mod y 100))))
(zerop (mod y 400)))
"yes"
"no"))
请注意,理想情况下,您的代码应该如下所示:
(princ "Enter a year: ")
(finish-output) ; make sure that output is done
(defvar *year* ; use the usual naming convention for
; global variables.
(let ((*read-eval* nil)) ; don't run code during reading
(read)))
(defun leap-year-p (y)
; your implementation here
; return a truth value
)
(print (if (leap-year-p *year*) "yes" "no"))
或者,最好不要在顶层处理函数调用和全局变量。为所有内容编写程序/函数。这样,您的代码自动地变得更加模块化、可测试和可重用
(defun prompt-for-year ()
(princ "Enter a year: ")
(finish-output)
(let ((*read-eval* nil))
(read)))
(defun leap-year-p (y)
; your implementation here
; return a truth value
)
(defun check-leap-year ()
(print (if (leap-year-p (prompt-for-year))
"yes"
"no")))
(check-leap-year)
错误消息很重要,请在描述错误/问题时说明报告的错误。我正在使用命令提示符和记事本。我试着运行你的代码,结果没有显示输出。我不知道为什么。在命令提示符中,您应该保持打印
。