Search code examples
recursionlispclisp

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))

Solution

  • 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)))))