Greasy 01
Greasy 01

Reputation: 11

Common Lisp: Recursive function returns nil

I'm trying to write a function that recursively returns the negative values of a list. This is what I have so far:

(defun neg-nums (L)
(if (null L) nil
  (let ((X (neg-nums (cdr L))))
         (if (< (car L) 0) (append (list (car L)) X)))))

(print (neg-nums (list 1 -2 3 -4)))

I tried the let function outside of the recursion, and it works fine, so I know its something to do with trying to make it recursive. right now, it just outputs NIL when it should output (-2 -4).

(PS, the print function is so when I load it as a file, I can see the result right away.)

Any help would be appreciated.

Upvotes: 0

Views: 93

Answers (1)

Greasy 01
Greasy 01

Reputation: 11

Apologies, I just realized that I needed an extra X in the last line. the correct answer is this:

(defun neg-nums (L)
(if (null L) nil
  (let ((X (neg-nums (cdr L))))
         (if (< (car L) 0) (append (list (car L)) X) X))))

(print (neg-nums (list 1 -2 3 -4)))

Upvotes: 1

Related Questions