Clojure reverse-flattening lists. E.g. '(1 2 3 4 5 6) to '( (1 2) (3 4) (5 6)

clojure

Solution

You can use `reduce` and `partition` :

(reduce #(partition %2 %1) '(1 2 3 4 5 6 7 8) [2 2])

Problem

Is there a core function or some idiomatic way to do a "reverse flattening" of a collection? E.g. I would like the following: ``` (by-two '(1 2 3 4 5 6)) ; evals to '( (1 2) (3 4) (5 6) ) ``` Of course the form in the above case would need an even number of elements or the function should do something sensible if presented with an odd-numbered collection. A generalized by-n function would be better of course. It's not clear to me whether there's any merit in trying to generalize the concept in depth as well or what's the best form to do so: ``` (by [2 2] '(1 2 3 4 5 6 7 8)) ; evals to '( ( (1 2) (3 4) ) ( (5 6) (7 8) ) ) (by [3 2 1 1 1] '(1 2 3 4 5 6)) ; evals to '(((((1 2 3) (4 5 6))))) ```

Original source