Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten nested lists in clojure?

Tags:

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})
  • Is there a way to turn an indeterminate number of nested list items into a single list? It would be nice if it could handle varying levels of nesting too.
  • Or simply a map-like function that ignores list level nesting, and operates on leaves?
  • Maybe I should be doing something different at the function level to build the data? (E.g., reduce instead of map)
like image 574
Jason Basanese Avatar asked Feb 04 '26 07:02

Jason Basanese


2 Answers

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.

like image 152
amalloy Avatar answered Feb 06 '26 07:02

amalloy


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.

like image 20
Nathan Davis Avatar answered Feb 06 '26 07:02

Nathan Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!