0

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.

1 Answer 1

1

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)))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.