Another flatten thread! Sorry..

Hello all, before I realized there was a flatten in the master branch
(and before I looked at contrib) I wrote this pretty standard code:

(defn my-flatten [coll]
 (lazy-seq
   (when-let [coll (seq coll)]
     (let [x (first coll)]
       (if (sequential? x)
         (concat (my-flatten x) (my-flatten (next coll)))
         (cons x (my-flatten (next coll))))))))

(There's very similar versions on the boards. I'm not claiming this is
anything amazing or unique.)

It's not as elegant as what's in core, but in my micro benchmarks (ran
on my laptop; 2.26 core 2 and 4gb ram) it seems to perform a bit
better, _especially_ in the already flattened case. It behaves just
like core/flatten except that it doesn't return an empty list when
passed a map or set, it just returns whatever you gave it but with the
top level converted to a seq. I'm pretty much a clojure noob, so are
there any hidden detractors of this implementation as opposed to the
version introduced in 1.2?

Also, quick note, if you swap the call to sequential? with seqable?
from contrib/core, it flattens maps and sets like you'd expect as
well.
Here is how it looks
user=> (my-flatten #{1 {2 3} 4 [5 6 7 #{8 {9 10}}]})
(1 2 3 4 5 6 7 9 10 8)

And for the micro-benchmarks (using "sequential?"):

user=> (time (dotimes [_ 1e7] (flatten [1 2 3 4])))
"Elapsed time: 14,661.592 msecs"
nil

user=> (time (dotimes [_ 1e7] (my-flatten [1 2 3 4])))
"Elapsed time: 922.268 msecs"
nil

user=> (time (dotimes [_ 1e7] (flatten [1 [2 [3 [4 [5 [6 [7 [8]
[[[9]]] 10 [11] 12 [13 14 [15]]]]]]]]])))
"Elapsed time: 18,147.959 msecs"
nil

user=> (time (dotimes [_ 1e7] (my-flatten [1 [2 [3 [4 [5 [6 [7 [8]
[[[9]]] 10 [11] 12 [13 14 [15]]]]]]]]])))
"Elapsed time: 6,088.914 msecs"
nil

user=> (time (dotimes [_ 1e7] (flatten [[1 2 3 4 5 6 7 8 9 10]])))
"Elapsed time: 11,696.693 msecs"
nil

user=> (time (dotimes [_ 1e7] (my-flatten [[1 2 3 4 5 6 7 8 9 10]])))
"Elapsed time: 1,533.983 msecs"
nil

Thoughts?

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to