Basic LISP recursion, enumerate values greater than 3
Basic LISP recursion, enumerate values greater than 3
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))
3 Answers
3
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.
(6)
foo
You can easily fix it by making foo return 0 instead of lst when lst is empty.
foo
0
lst
lst
As a style note: Mixing cond and if like this, seems a bit redundant. I would write it like this, using only cond instead:
cond
if
cond
(defun foo (lst)
(cond
((null lst)
0)
((> (car lst) 3)
(1+ (foo (cdr lst))))
(T
(foo (cdr lst)))))
The best on-line resource for common lisp is (probably) "The HyperSpec" ( lispworks.com/documentation/HyperSpec/Front ) and is close to the most comprehensive description of CL.
– Vatine
Nov 19 '10 at 10:48
Some stylistic points:
DEFUN
NULL
if
cond
cond
lst
list
If you were programming this for real, of course you'd use count-if:
count-if
(count-if #'(lambda (x) (> x 3)) '(0 1 2 3 4 5 6))
==> 3
Sorry about the stylistic issues (first program)... perhaps my professor learned LISP in 1958--I chuckled though. I believe "count-if" is outside the scope of the functions we're allowed to use.
– toast
Nov 18 '10 at 23:42
One save you can have on duplication of the recursive call:
(defun foo (l)
(if (null l) 0 ; if list is empty, return 0
(+ (if (> (car l) 3) 1 0) ; else +1 if condition is satisfactory
(foo (cdr l))))) ; plus the result from the rest
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I did not know cond could work that way. All of the online resources are scattered about the internet and not easy to comprehend...
– toast
Nov 19 '10 at 0:16