Jason Basanese
Jason Basanese

Reputation: 710

How to flatten nested lists in clojure?

I have a function that returns results that look something like this:

(({:one 1}) ({:two 2} ({:three 3} {:four 4})))

Is there an easy/idiomatic/efficient way to flatten the above list into a single list:

({:one 1} {:two 2} {:three 3} {:four 4})

Upvotes: 2

Views: 3449

Answers (2)

Nathan Davis
Nathan Davis

Reputation: 5766

Is there a way to turn an indeterminate number of nested list items into a single list?

flatten takes a nested sequence and returns a single, flat sequence containing the "leaves" (i.e., non-sequential items).

Or simply a map-like function that ignores list level nesting, and operates on leaves?

I don't think there's one provided by Clojure, but you could always compose map and flatten:

(comp map flatten)

Maybe I should be doing something different at the function level to build the data?

Since you did not provide any details on how you build the data, it is impossible for us to say one way or another. But, this is probably a good idea.

Again, it's impossible to give you any hard advice. But I usually find mapcat (or just concat) to be useful in these situations.

Upvotes: 1

amalloy
amalloy

Reputation: 91857

While you can use flatten to fix your broken nesting (in most cases, anyway, depending on what your data is shaped like), it is almost always better to build the list properly to begin with. Try asking another question about how to avoid generating this silly list to begin with.

Upvotes: 12

Related Questions