Flatten a list: Difference between revisions

→‎{{header|Common Lisp}}: add a fourth example
(→‎{{header|Common Lisp}}: remove one of my previous implementations that does not give the correct solution. Add an example.)
(→‎{{header|Common Lisp}}: add a fourth example)
Line 682:
result)))</lang>
 
ThisThe following version is tail recursive and functional.
<lang lisp>(defun flatten-trf (x &optional stack out)
(cond ((consp x) (flatten-trf (rest x) (cons (first x) stack) out))
(x (flatten-trf (first stack) (rest stack) (cons x out)))
(stack (flatten-trf (first stack) (rest stack) out))
(t out)))</lang>
 
The next version is imperative, iterative and does not make use of a stack. It is faster than the versions given above.
<lang lisp>(defun flatten (obj)
(do* ((result (list obj))
(node result))
((null node) (delete nil result))
(cond ((consp (car node))
(when (cdar node) (push (cdar node) (cdr node)))
(setf (car node) (caar node)))
(t (setf node (cdr node))))))</lang>
The above implementations of flatten give the same output on nested proper lists.
{{Out}}