Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Lisp: Why does this function cause infinite recursion?

I am trying to write a function (lnn; list-not-nil) similar to list that only appends values that are not nil.

(list nil 3) --> (NIL 3)
(lnn nil 3) --> (3)

Here is the code I have so far. For some reason it causes infinite recursion on any input that I try.

(defun lnn (&rest items)
  (lnn-helper nil items))

(defun lnn-helper (so-far items)
   (cond ((null items)
           so-far)
     ((null (car items))
      (lnn-helper so-far (cdr items)))
     (t (lnn-helper (append so-far (list (car items))) (cdr items)))))

Any ideas? Thanks very much.

like image 768
Miriam Avatar asked Nov 27 '25 13:11

Miriam


1 Answers

(defun lnn-helper (so-far &rest items)
  ...)

With this argument list, items will never be nil if you always call lnn-helper with two arguments. Remove the &rest specifier, and it'll work.

like image 182
Matthias Benkard Avatar answered Nov 30 '25 13:11

Matthias Benkard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!