Search code examples
lispcommon-lispclisp

If condition with and operator


How to use IF condition with AND operator? I'm getting an error

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


Solution

  • Note that your code should ideally look like this:

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

    Alternatively it also is a good idea to not work on the top-level with function calls and global variables. Write procedures/functions for everything. That way your code automatically is more modular, testable and reusable.

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