Re: flattening a nested list functionally
- From: Andras Simon <asimon@xxxxxxxxxxx>
- Date: 07 Dec 2006 00:40:38 +0100
"John Thingstad" <john.thingstad@xxxxxxxxx> writes:
Wrote this function to flatten a nested list.
(defparameter *test-list* '((1 2 3) (4 5 6 (7 8 9)) 10))
(defun flatten-reverse (element)
(let ((new-element nil))
(mapc
(lambda (e)
(if (consp e)
(setf new-element (append (flatten-reverse e) new-element))
(push e new-element)))
element)
new-element))
(defun flatten (list)
(nreverse (flatten-reverse list)))
CL-USER 27 > (flatten *test-list*)
(1 2 3 4 5 6 7 8 9 10)
Not too bad if I may say so but what I was trying to do was write it in a
purely functional style. How do I do this without introducing a variable?
(defun flatten (list)
(mapcan #'(lambda (e) (if (consp e) (flatten e) (list e))) list))
Doesn't look too good, but it's a start.
Andras
.
- References:
- flattening a nested list functionally
- From: John Thingstad
- flattening a nested list functionally
- Prev by Date: Re: Common Lisp from a Unix perspective - barriers to using CL
- Next by Date: Re: lost adding float
- Previous by thread: flattening a nested list functionally
- Next by thread: Re: flattening a nested list functionally
- Index(es):
Relevant Pages
|