I need a recursive LISP function that enumerates the number of elements in any list of numbers > 3. I'm not allowed to use lets, loops or whiles and can only use basic CAR, CDR, SETQ, COND, CONS, APPEND, PROGN, LIST...
This is my attempt at the function:
(defun foo (lst)
(COND ((null lst) lst)
(T (IF (> (CAR lst) 3)
(1+ (foo (CDR lst)))
(foo (CDR lst)) ) ) ) )
The function call:
(foo '(0 1 2 3 4 5 6))
Your code is pretty close to correct, just a small mistake in the base case:
For the empty list you return the empty list. So if you have the list (6)
, you add 6 to foo
of the empty list, which is the empty list. That does not work because you can't add a number to a list.
You can easily fix it by making foo
return 0
instead of lst
when lst
is empty.
As a style note: Mixing cond
and if
like this, seems a bit redundant. I would write it like this, using only cond
instead:
(defun foo (lst)
(cond
((null lst)
0)
((> (car lst) 3)
(1+ (foo (cdr lst))))
(T
(foo (cdr lst)))))
Some stylistic points:
DEFUN
and NULL
?if
inside the last branch of your cond
. This is redundant. Since the purpose of cond
is testing conditions, why not use it?lst
to avoid conflicting with the built-in function list
.If you were programming this for real, of course you'd use count-if
:
(count-if #'(lambda (x) (> x 3)) '(0 1 2 3 4 5 6))
==> 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With