bug-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

bug#33309: Add flatten-list?


From: Basil L. Contovounesios
Subject: bug#33309: Add flatten-list?
Date: Mon, 10 Dec 2018 22:42:14 +0000
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux)

[Sorry, Alex, for sending this to you twice - I accidentally made my
 last message a narrow, rather than wide, reply.]

Alex Branham <alex.branham@gmail.com> writes:

> Thanks for the feedback, everyone.

Thanks for working on this.

> Here's a patch that implements `flatten-tree' which always returns a
> list and recurses into conses.

Given Emacs' recursive limitations, wouldn't an iterative implementation
be better?  For instance, the following currently blows
max-specpdl-size:

  (length (flatten-tree (make-list 800 nil)))

How about something like the following?

diff --git a/lisp/subr.el b/lisp/subr.el
index f7eac75305..3fed3bc436 100644
--- a/lisp/subr.el
+++ b/lisp/subr.el
@@ -5453,10 +5453,15 @@ flatten-tree
 This always returns a list containing all the elements of TREE.
 \(flatten-tree \\='(1 (2 3 (4 5 (6))) 7))
 => (1 2 3 4 5 6 7)"
-  (cond ((null tree) nil)
-        ((consp tree) (append (flatten-tree (car tree))
-                              (flatten-tree (cdr tree))))
-        (t (list tree))))
+  (let (elems)
+    (setq tree (list tree))
+    (while (let ((elem (pop tree)))
+             (cond ((consp elem)
+                    (setq tree (cons (car elem) (cons (cdr elem) tree))))
+                   (elem
+                    (push elem elems)))
+             tree))
+    (nreverse elems)))
 
 ;; Technically, `flatten-list' is a misnomer, but we provide it here
 ;; for discoverability:
-- 
Basil

reply via email to

[Prev in Thread] Current Thread [Next in Thread]