What is an idiomatic way to merge (or retrieve the union of) two lists (or sequences) in Clojure?
(merge l1 l2)
doesn't seem to be the solution:
a=> (merge '(1 2 3) '(2 3 4))
((2 3 4) 1 2 3)
What is an idiomatic way to merge (or retrieve the union of) two lists (or sequences) in Clojure?
(merge l1 l2)
doesn't seem to be the solution:
a=> (merge '(1 2 3) '(2 3 4))
((2 3 4) 1 2 3)
One option is flatten:
One thing to be aware of is that it will flatten deeply nested collections:
But works well for maps:
One way to get the union of two lists is to use
union
or if you want to get a list
If you don't mind duplicates, you can try concat :
I think andih's solution works great. Here is an alternate way because hey why not. It uses
concat
anddistinct
:If what you want is actually distinct unsorted data (sets), you should be using Clojure's set data structure instead of vectors or lists. And as andih suggested indirectly, there is a core library for set operations: http://clojure.github.com/clojure/clojure.set-api.html
If sets are for whatever reason not what you want, then read on. Careful with
concat
when you have a significant amount of data in your sequences, and consider usinginto
which is much better optimized as a vector merging algorithm. I don't know why concat is not implemented using into (or better yet-- why does concat even exist? BTW while into is significantly faster than concat, it is still way way slower than conj. Bagwell's RRB trees, compatible with both Clojure and Scala, will solve this problem, but are not yet implemented for Clojure).To rephrase Omri's non-set solution in terms of 'into':