I am designing a simple function (for class, so please no complete done-for-you answers) that returns the first odd integer in a list, or 'none if there are none.
I have a working code for finding the odd number:
(defun first-odd (lst)
(do ((numbers lst (cdr numbers)))
((oddp (car numbers)) (car numbers))))
but what I can't seem to figure out is where to place the IF conditional (which is required for the assignment) to produce "NONE" if the list is only even #s, or presumably NIL. Do I make the exit point of the DO itself the IF conditional? Or does it go before/after?
I'm working on something like this (although I have a feeling it's wrong):
(defun first-odd (lst)
(do ((numbers lst (cdr numbers)))
((if (oddp (car numbers))
(car numbers)
(print 'none)))))
Or can someone advise me on 'where' to place the IF? Sorry for the truly beginner takes, but the prof didn't provide much documentation for DO and I've been scratching my head all weekend. Thanks in advance.
DO takes three arguments: the first one is the list of variables with their initial values and the subsequent values; the second is the terminating condition, i.e. when to exit the loop and the result to return; the third one is the body of the loop, and it's optional.
The second element contains an implicit if.
Your first code looks good with one exception: have you considered what happens if there are no odd elements in the list? You need then to test for the end of the list (i.e. when list is nil). Then, the result will depend on whether you exited the loop because an odd number was found, or a nil list. That's where you can use IF.