What's the one-level sequence flattening function in Clojure? I am using apply concat for now, but I wonder if there is a built-in function for that, either in standard library or clojure-contrib.
My general first choice is apply concat. Also, don't overlook (for [subcoll coll, item subcoll] item) -- depending on the broader context, this may result in clearer code.
There's no standard function. apply concat is a good solution in many cases. Or you can equivalently use mapcat seq.
The problem with apply concat is that it fails when there is anything other than a collection/sequential is at the first level:
(apply concat [1 [2 3] [4 [5]]]) => IllegalArgumentException Don't know how to create ISeq from: java.lang.Long...   Hence you may want to do something like:
(defn flatten-one-level [coll]     (mapcat  #(if (sequential? %) % [%]) coll))  (flatten-one-level [1 [2 3] [4 [5]]]) => (1 2 3 4 [5])   As a more general point, the lack of a built-in function should not usually stop you from defining your own :-)
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