I build this function to check if all the "var" on the list are numbers. This what i tried to do
(defun check6 (list)
(if (null list) 'TRUE)
(if (not (numberp(first list))) nil)
(check6 (rest list)))
But always i get stack overflow.
Why please?
The stack overflow is due to the fact that you have several unrelated
if
, so that they produce a value which is not consumed and continue to execute the rest of the body of the function. This means thatcheck6
is never terminated and causes the overflow.If you paste your code in a proper editor, which automatically align the lines of code, you could discover that the editor produces this alignment:
If you want to use the
if
special operator, you should remember that it has two cases, for when the condition is true and when it is false, and should nest the forms in this way (again with the proper alignment):But Common Lisp has the much more convenient syntax for concatenating conditions,
cond
:Finally, note that there are other ways to solve your problem, either by using iteration:
or with high-level functions, in a still more concise way:
You should definitely take a close look at the different ways that Renzo has written the function, but your code can be patched up by returning from the function early:
You get a stack overflow because the function never terminates.
The result of a function in Lisp is the value of the last expression in the function's body.
In your case that is
(check6 (rest list))
.I suspect that you're thinking of some other language, where this might be written something like (in a completely fictitious language):
but your conditionals don't return their results from the function; their results are just discarded since you're not doing anything with them.
In the fictitious language above, your function would be
where you can probably see what's going wrong.
I personally find multi-pronged conditionals hard to follow compared to a logical expression.
If you write down the conditions for when a list is all numbers:
it's straightforward to translate into Lisp:
In the fictitious language,
But once you get acquainted with higher-order functions, you would probably write
which might be the most Lisp-y solution.