Search code examples
loopsfor-loopreturnlispcommon-lisp

LISP Loop For Returns NIL


I have this small program that prints triangles either forwards or backwards depending on whether the input is positive or negative. It works perfectly, except at the end of every loop it prints NIL. I tried changing the bounds of the loop, but every when I do it effects the size of the triangle. Is there any solution to this? Please find the code below.

(defun triangle(k) 
    (cond ((or(not(integerp k)) (= k 0)) '("invalid number; please enter a positive or a negative integer"))
          ((< k -1) 
             (loop for x from k to -1 do
                 (loop for y from k to -1 do 
                       (if (< y x) 
                           (princ #\Space)
                           (princ '*) 
                       ) 
                     
                  ) 
                (terpri)
              )
          )  
        
         ((or (= k 1) (= k -1)) '*) 
         (t(loop  for x from 0 to k do 
               (loop for y from 0 to k do  
                 (if (< x y)    
                     (princ '*) 
                 )
                ) 
                (terpri)
           ) 
         ) 
    ) 
)

Solution

  • (defun triangle (k) 
      (cond ((or (not (integerp k))
                 (= k 0))
             '("invalid number; please enter a positive or a negative integer"))
            ((< k -1) 
             (loop for x from k to -1 do
                   (loop for y from k to -1 do 
                         (if (< y x) 
                             (princ #\Space)
                           (princ '*))) 
                    (terpri)))
            ((or (= k 1) (= k -1))
             '*) 
            (t
             (loop for x from 0 to k do 
                   (loop for y from 0 to k do  
                         (if (< x y)    
                             (princ '*))) 
                   (terpri))))
      (values))
    

    Example:

    CL-USER 8 > (triangle 3)
    ***
    **
    *
    
    
    CL-USER 9 >