I am attempting to write a small recursive program that tests a list and returns t if every element is an atom. The problem I am having is that when the function receives an empty list, it returns t instead of the desired result of nil. I cannot come up with a way to have it return nil for an initially empty list and still function properly in a recursive manner.
(defun only-atoms (in)
(if (null in)
t
(and (atom (first in)) (only-atoms (cdr in)) )
)
)
The function can be implemented without recursion using e.g.
every, as in:When it comes to your stated problem that the function returns
Tinstead of the desired result ofNILwhen the function is called with an empty list:Your recursive implementation explicitly returns
Tif(null in)is true, which explains your finding. Simply change it to the desired valueNIL. Consider changing theifconstruct toand.Only make the recursive call when the list has more than one item. A well placed test for
(rest in)will do. Provide a true value instead of making the recursive call if the list is at its last item.Carefully locate the
only-atomscall to ensure that the function can be tail-recursive.For example: