Reputation: 113
I'm a newbie in lisp. I've written a 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 I do avoid 'nil' from getting added to the list? I'm supposed to make a single recursive function.
Upvotes: 1
Views: 106
Reputation: 14065
The problem is that NIL
, while doubling as the empty list
, is still an atom
.
CL-USER> (atom nil)
T
CL-USER> (atom '())
T
CL-USER>
If you need to ignore it, you'll need to change that second clause to check for NIL
specifically.
...
((and (atom (first list)) (not (null (first list)))) ...)
...
Another option is changing your base case so that it gracefully handles NIL
s in its first return value.
Upvotes: 1
Reputation: 5477
Your problem is that NIL is both an empty list and an atom. So (atom nil)
is true, but you want to view it as an empty list instead. To fix this, you need to handle (first list)
being nil separately.
Upvotes: 1
Reputation: 48745
(atom nil) ; ==> T
and of course since ()
is nil
you need to make a new base case that just recurse instead of consing when it's nil.
Upvotes: 1