Search code examples
loopslispcommon-lisp

Simple Lisp Loop


(defun add-them(a b)

    (loop
        (if(< a 15)
           (setq a (* a b))
           (write a)
        )
        (when(> a 15)
            
            (return a))
    
    )

)
(print (add-them 3 5))

Having issues with this code block I want to be able to check if a is less than 15 and multiply it by b if it is less than 15 in a loop. Then I want to return it if it is greater than 15. I've never used lisp before and this is for an assignment so please do not outright give me the answer, just guidance.


Solution

  • Check your syntax. The if statement takes three arguments: the condition, the code when the condition is true and the code when the condition is false.

    (if <test>
      <do-this-when-true>
      <do-this-when-false> )
    

    Each one of these must be a list, so if you need to do multiple things surround it with e.g. progn. In your example it will look like this

    (loop
            (if (< a 15)
               (progn
                 (setq a (* a b))
                 (write a))
               (return a))
        )
    

    As mentioned in another comment, this is not very lispy but it should be a good start.