如果条件和运算符

问题描述

如何将 IF 条件与 AND 运算符一起使用? 我收到一个错误

(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 中使用该函数,则可以省略 print

(defun leap-year (y)
  (if (and (= 0 (mod y 400)) (= 0(mod y 4)))
      "Is a leap year"
      "Is not"))

最后,请注意闰年的检查是 incorrect。正确的定义可能如下:

(defun leap-year (y)
  (cond ((/= 0 (mod y 4)) "no")
        ((/= 0 (mod y 100)) "yes")
        ((/= 0 (mod y 400)) "no")
        (t "yes")))

或者,使用 if

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