LISP main recursion, list values ​​greater than 3

I need a recursive LISP function that lists the number of elements in any list of numbers> 3. I am not allowed to use let, loop or whiles and can only use basic CAR, CDR, SETQ, COND, CONS, APPEND, PROGN, LIST ...

This is my attempt to function:

(defun foo (lst) (COND ((null lst) lst) (T (IF (> (CAR lst) 3) (1+ (foo (CDR lst))) (foo (CDR lst)) ) ) ) ) 

Function call:

 (foo '(0 1 2 3 4 5 6)) 
+4
source share
2 answers

Your code is pretty close to correct, just a small mistake in the base case:

In an empty list, you return an empty list. Therefore, if you have a list (6) , you add 6 to foo from an empty list, which is an empty list. This does not work because you cannot add a number to the list.

You can easily fix this by making foo return 0 instead of lst when lst empty.

As a side note: Mixing cond and if like this seems a bit redundant. I would write it like this using cond instead:

 (defun foo (lst) (cond ((null lst) 0) ((> (car lst) 3) (1+ (foo (cdr lst)))) (T (foo (cdr lst))))) 
+5
source

Some stylistic points:

  • No need to embed some Lisp built-in uppercase. This is not 1958!
  • But if you are going to embed the built-in uppercase, why not DEFUN and NULL ?
  • You have an if inside the last branch of your cond . This is redundant. Since cond purpose is to test conditions, why not use it?
  • You do not need to highlight closing parentheses. No one has parentheses these days; we have parentheses corresponding to the editors.
  • Lisp has separate namespaces for functions and values, so you do not need to call your lst argument to avoid a conflict with the built-in list function.

If you really programmed this, of course, you would use count-if :

 (count-if #'(lambda (x) (> x 3)) '(0 1 2 3 4 5 6)) ==> 3 
+4
source

All Articles