Search code examples
lispcommon-lispclisp

Checking for even and odd values in a loop with Lisp


I do not understand why the following lisp program displays 15 lines of output as opposed to 10:

(defparameter x 1)
(dotimes (x 10)
  (if (oddp x)
    (format t "x is odd~%"))
    (format t "x is even~%"))

I am using CLISP 2.49 on a Windows 10 machine.


Solution

  • Current:

    (if (oddp x)
        (format t "x is odd~%"))    ; <- extra parenthesis
        (format t "x is even~%"))
    

    Wanted:

    (if (oddp x)
        (format t "x is odd~%")
        (format t "x is even~%"))
    

    You are escaping the if form before the else statement so the else statement gets always printed while the if statement gets printed 5 times.