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})
map-like function that ignores list level nesting, and operates on leaves?reduce instead of map)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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With