lisp - How to avoid NIL from getting added to the list? -
i'm newbie in lisp. i've written flatten function in lisp.
(defun flatten (list) (cond ((null list) nil) ((atom (first list)) (cons (first list) (flatten (rest list)))) (t (append (flatten (first list)) (flatten (rest list))))))
input- (flatten '(a () b (c d)))
expected output- (a b c d)
my output- (a nil b c d)
what should avoid 'nil' getting added list? i'm supposed make single recursive function.
the problem nil
, while doubling the empty list
, still atom
.
cl-user> (atom nil) t cl-user> (atom '()) t cl-user>
if need ignore it, you'll need change second clause check nil
specifically.
... ((and (atom (first list)) (not (null (first list)))) ...) ...
another option changing base case gracefully handles nil
s in first return value.
Comments
Post a Comment